package com.sayimo.maker.mall.orders.service.impl;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.JDOMException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.sayimo.framework.common.Constants;
import com.sayimo.framework.common.MessageObject;
import com.sayimo.framework.common.util.VerifyCodeUtil;
import com.sayimo.framework.exception.BaseAppException;
import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.activity.dao.BaseCutDao;
import com.sayimo.maker.activity.dao.BaseGroupBuyDao;
import com.sayimo.maker.activity.dao.BaseSeckillGoodsDao;
import com.sayimo.maker.activity.dao.BaseSeckillTimesDao;
import com.sayimo.maker.base.dao.BaseConfigDao;
import com.sayimo.maker.base.dao.EmsListDao;
import com.sayimo.maker.base.vo.EmsList;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.GeneratorUtils;
import com.sayimo.maker.commons.ali.pay.ALiPay;
import com.sayimo.maker.commons.ali.pay.ALiTransfer;
import com.sayimo.maker.commons.ali.pay.AliScancodePay;
import com.sayimo.maker.commons.ali.pay.AliWapPay;
import com.sayimo.maker.commons.push.Demo;
import com.sayimo.maker.commons.utils.Base64Utils;
import com.sayimo.maker.commons.utils.CbcEncrypt;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.commons.utils.KdniaoTrackQueryAPI;
import com.sayimo.maker.commons.utils.MD5Util;
import com.sayimo.maker.commons.utils.PropertiesUtils;
import com.sayimo.maker.commons.utils.WXUtil;
import com.sayimo.maker.commons.utils.XMLUtil;
import com.sayimo.maker.commons.wx.pay.WXPay;
import com.sayimo.maker.commons.wx.pay.WXScanCodePay;
import com.sayimo.maker.mall.goods.dao.GoodsListInterfaceDao;
import com.sayimo.maker.mall.goods.dao.GoodsNormsInfoInterfaceDao;
import com.sayimo.maker.mall.goods.dao.GoodsNormsValueStockInterfaceDao;
import com.sayimo.maker.mall.goods.dao.impl.GoodsCommentInterfaceImplDao;
import com.sayimo.maker.mall.goods.service.GoodsListInterfaceService;
import com.sayimo.maker.mall.goods.service.GoodsNormsInfoInterfaceSerice;
import com.sayimo.maker.mall.goods.service.GoodsNormsValueStockInterfaceService;
import com.sayimo.maker.mall.goods.service.ShoppingCartService;
import com.sayimo.maker.mall.goods.vo.GoodsList;
import com.sayimo.maker.mall.goods.vo.GoodsNormsValueStock;
import com.sayimo.maker.mall.goods.vo.ShoppingCartNormsValue;
import com.sayimo.maker.mall.orders.dao.OrdersGoodsInfoInterfaceDao;
import com.sayimo.maker.mall.orders.dao.OrdersListInterfaceDao;
import com.sayimo.maker.mall.orders.service.OrderBrokerageInterfaceService;
import com.sayimo.maker.mall.orders.service.OrderPeriodInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersFlowInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersGoodsInfoInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersGoodsNormsInfoInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersListInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersReceivingAddressInterfaceService;
import com.sayimo.maker.mall.orders.vo.GenerateOrdersFlowParams;
import com.sayimo.maker.mall.orders.vo.GenerateOrdersGoodsParams;
import com.sayimo.maker.mall.orders.vo.GenerateOrdersResult;
import com.sayimo.maker.mall.orders.vo.GenerateOrdersReturnParams;
import com.sayimo.maker.mall.orders.vo.GenerateReceivingAddressResult;
import com.sayimo.maker.mall.orders.vo.OrdersFlow;
import com.sayimo.maker.mall.orders.vo.OrdersGoodsInfo;
import com.sayimo.maker.mall.orders.vo.OrdersGoodsNormsInfo;
import com.sayimo.maker.mall.orders.vo.OrdersList;
import com.sayimo.maker.mall.orders.vo.OrdersReceivingAddress;
import com.sayimo.maker.mall.search.service.SearchService;
import com.sayimo.maker.user.dao.CustomerInterfaceDao;
import com.sayimo.maker.user.dao.EnterpriseInfoDao;
import com.sayimo.maker.user.dao.EnterpriseWalletIncomeExpendRecordInterfaceDao;
import com.sayimo.maker.user.dao.EnterpriseWalletInterfaceDao;
import com.sayimo.maker.user.dao.MemberCustomerInterfaceDao;
import com.sayimo.maker.user.dao.WalletIncomeExpendRecordInterfaceDao;
import com.sayimo.maker.user.service.CustomerInterfaceService;
import com.sayimo.maker.user.service.ProvinceInterfaceService;
import com.sayimo.maker.user.service.ReceivingAddressInterfaceService;
import com.sayimo.maker.user.service.WalletIncomeExpendRecordService;
import com.sayimo.maker.user.service.WalletInterfaceService;
import com.sayimo.maker.user.vo.Customer;
import com.sayimo.maker.user.vo.EnterpriseInfo;
import com.sayimo.maker.user.vo.EnterpriseWallet;
import com.sayimo.maker.user.vo.EnterpriseWalletIncomeExpendRecord;
import com.sayimo.maker.user.vo.ReceivingAddress;
import com.sayimo.maker.user.vo.Wallet;
import com.sayimo.maker.user.vo.WalletIncomeExpendRecord;

/**
 * @Copyright (c) 2016 广东省尚一互联网有限公司
 * @Project: schoolmallapi
 * @ClassName: OrdersListInterfaceImplService
 * @Description: 订单
 * @Author: 王瑞清
 * @Date: 日期：2016年1月4日 时间：下午5:13:17
 * @Version 1.0.0
 */
@Service(value = "ordersListInterfaceService")
@SuppressWarnings("all")
public class OrdersListInterfaceImplService implements OrdersListInterfaceService {

	private static Log logger = LogFactory.getLog(OrdersListInterfaceImplService.class);

	// 广州省编码开头两位字符
	private static final String gzcode = "44";

	@Resource(name = "provinceInterfaceImplService")
	private ProvinceInterfaceService provinceInterfaceService;

	@Resource(name = "ordersListInterfaceDao")
	private OrdersListInterfaceDao ordersListInterfaceDao;

	@Resource(name = "ordersGoodsInfoInterfaceService")
	private OrdersGoodsInfoInterfaceService ordersGoodsInfoInterfaceService;

	@Resource(name = "goodsNormsInfoInterfaceSerice")
	private GoodsNormsInfoInterfaceSerice goodsNormsInfoInterfaceSerice;

	@Resource(name = "goodsNormsValuesInterfaceService")
	private GoodsNormsValueStockInterfaceService goodsNormsValueStockInterfaceService;

	@Resource(name = "ordersFlowInterfaceService")
	private OrdersFlowInterfaceService ordersFlowInterfaceService;

	@Resource(name = "shoppingCartServiceImpl")
	private ShoppingCartService shoppingCartService;

	@Resource(name = "goodsListInterfaceImplService")
	private GoodsListInterfaceService goodsListInterfaceImplService;

	@Resource(name = "customerInterfaceImplService")
	private CustomerInterfaceService customerInterfaceImplService;

	@Resource(name = "walletInterfaceService")
	private WalletInterfaceService walletInterfaceImplService;

	@Resource(name = "receivingAddressInterfaceImplService")
	private ReceivingAddressInterfaceService receivingAddressInterfaceService;

	@Resource(name = "ordersReceivingAddressInterfaceService")
	private OrdersReceivingAddressInterfaceService ordersReceivingAddressInterfaceService;

	@Resource(name = "ordersGoodsNormsInfoInterfaceService")
	private OrdersGoodsNormsInfoInterfaceService ordersGoodsNormsInfoInterfaceService;

	@Resource(name = "orderPeriodInterfaceImplService")
	private OrderPeriodInterfaceService orderPeriodInterfaceService;

	@Resource(name = "transactionManager")
	private DataSourceTransactionManager transactionManager;

	@Autowired(required = false)
	private HttpServletRequest request;

	@Resource(name = "walletIncomeExpendRecordServiceImpl")
	private WalletIncomeExpendRecordService walletIncomeExpendRecordServiceImpl;

	@Resource(name = "orderBrokerageInterfaceService")
	private OrderBrokerageInterfaceService orderBrokerageInterfaceService;

	@Autowired
	private CustomerInterfaceDao customerInterfaceImplDao;
	/*
	 * @Resource(name = "couponCustomerServiceImpl") private
	 * CouponCustomerService couponCustomerService;
	 */

	@Resource(name = "emsListDao")
	private EmsListDao emsListDao;

	@Resource(name = "enterpriseInfoDao")
	private EnterpriseInfoDao enterpriseInfoDao;

	@Resource(name = "ordersGoodsInfoInterfaceDao")
	private OrdersGoodsInfoInterfaceDao ordersGoodsInfoInterfaceDao;

	@Resource(name = "goodsListInterfaceImplDao")
	private GoodsListInterfaceDao goodsListInterfaceDao;

	@Resource(name = "goodsNormsInfoInterfaceDao")
	private GoodsNormsInfoInterfaceDao goodsNormsInfoDao;

	@Resource(name = "goodsNormsValueStockInterfaceDao")
	private GoodsNormsValueStockInterfaceDao goodsNormsValueStockInterfaceDao;

	@Resource(name = "baseConfigDao")
	private BaseConfigDao baseConfigDao;

	@Resource(name = "searchService")
	private SearchService searchService;

	@Resource(name = "goodsCommentInterfaceImplDao")
	private GoodsCommentInterfaceImplDao goodsCommentInterfaceImplDao;

	@Autowired
	private BaseSeckillTimesDao baseSeckillTimesDao;

	@Autowired
	private BaseSeckillGoodsDao baseSeckillGoodsDao;
	@Autowired
	private BaseGroupBuyDao baseGroupBuyDao;
	@Autowired
	private BaseCutDao baseCutDao;
	@Autowired
	private MemberCustomerInterfaceDao memberCustomerInterfaceDao;

	@Resource(name = "walletIncomeExpendRecordInterfaceDao")
	private WalletIncomeExpendRecordInterfaceDao walletIncomeExpendRecordInterfaceDao;
	@Resource(name = "enterpriseWalletInterfaceDao")
	private EnterpriseWalletInterfaceDao enterpriseWalletInterfaceDao;

	@Resource(name = "enterpriseWalletIncomeExpendRecordInterfaceDao")
	EnterpriseWalletIncomeExpendRecordInterfaceDao enterpriseWalletIncomeExpendRecordInterfaceDao;

	/**
	 * 查询修改所有支付成功但订单还是“未支付”的订单
	 * 
	 * 作者: 陈培永 日期：2015年9月22日 下午14:22
	 * 
	 * @param request
	 * @return
	 * @return
	 * @throws ServiceException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String updatePaySuccessOrder(Integer customerId) throws ServiceException {
		StringBuffer sBuffer = new StringBuffer();
		try {
			List<OrdersList> ordersLists = ordersListInterfaceDao.queryMemberCustomerOrderList(customerId, 1);
			if (ordersLists != null && !ordersLists.isEmpty()) {
				List<OrdersList> paramOrdersLists = new ArrayList<OrdersList>();

				for (Iterator iterator = ordersLists.iterator(); iterator.hasNext();) {
					OrdersList ordersList = (OrdersList) iterator.next();

					// 支付但是订单状态为“未支付”
					if (orderQuery(ordersList.getOrdersNo())) {
						paramOrdersLists.add(ordersList);
					}
				}
				if (!CollectionUtils.isEmpty(paramOrdersLists)) {
					for (OrdersList ordersList : paramOrdersLists) {
						ordersList.setStatus(2); // 已付款
						ordersListInterfaceDao.updateOrdersList(ordersList);
						ordersFlowInterfaceService
								.insertOrdersFlow(new GenerateOrdersFlowParams(ordersList.getId(), customerId, 2));

						WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
						expendRecord.setExPend(ordersList.getSumMoney());
						expendRecord.setCustomerId(customerId);
						expendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
						expendRecord.setFromType(4);
						expendRecord.setOrderId(ordersList.getId());
						expendRecord.setOrderType(0);
						expendRecord.setCommet("来源订单号" + ordersList.getOrdersNo() + "的消费");
						walletIncomeExpendRecordServiceImpl.insertSelective(expendRecord);
						sBuffer.append(ordersList.getId() + ",");

						continue;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sBuffer.toString();
	}

	/**
	 * @Package com.sayimo.school.mall.module.order.service.impl
	 * @Author 龚益君
	 * @MethodName:orderQuery
	 * @Description:查询微信已支付，本地数据库依然未支付的订单
	 * @param ordersList
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 * @Date 2016年9月26日,下午3:03:19
	 */
	public boolean orderQuery(String ordersNo) throws Exception {
		String nonceStr = WXUtil.getNonceStr();
		SortedMap<Object, Object> sortedMap = new TreeMap<Object, Object>();
		sortedMap.put("appid", PropertiesUtils.getValue("APPID"));
		sortedMap.put("mch_id", PropertiesUtils.getValue("MCHID"));
		sortedMap.put("out_trade_no", ordersNo);
		sortedMap.put("nonce_str", nonceStr);
		String sign = WXUtil.createSign("UTF-8", sortedMap);
		sortedMap = new TreeMap<Object, Object>();
		sortedMap.put("appid", PropertiesUtils.getValue("APPID"));
		sortedMap.put("mch_id", PropertiesUtils.getValue("MCHID"));
		sortedMap.put("out_trade_no", ordersNo);
		sortedMap.put("nonce_str", nonceStr);
		sortedMap.put("sign", sign);
		String requestXML = WXUtil.getRequestXml(sortedMap);
		HttpClient client = new HttpClient();
		PostMethod myPost = new PostMethod("https://api.mch.weixin.qq.com/pay/orderquery");
		client.getParams().setSoTimeout(300 * 1000);
		String result = null;
		try {
			myPost.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
			int statusCode = client.executeMethod(myPost);
			if (statusCode == HttpStatus.SC_OK) {
				BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
				byte[] bytes = new byte[1024];
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				int count = 0;
				while ((count = bis.read(bytes)) != -1) {
					bos.write(bytes, 0, count);
				}

				byte[] strByte = bos.toByteArray();
				result = new String(strByte, 0, strByte.length, "utf-8");
				bos.close();
				bis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		/* 需要释放掉、关闭连接 */
		myPost.releaseConnection();
		client.getHttpConnectionManager().closeIdleConnections(0);
		if (!StringUtils.isEmpty(result)) {
			Map<String, String> map = XMLUtil.doXMLParse(result);

			if (map.get("return_code") != null && map.get("return_code").equals("SUCCESS")
					&& map.get("result_code") != null && map.get("result_code").equals("SUCCESS")
					&& map.get("trade_state") != null && map.get("trade_state").equals("SUCCESS")) { // 支付成功.但是订单状态还是待支付

				return true;
			}
		}
		return false;

	}

	/**
	 * @Title: insertOrdersSingle
	 * @Author: 王瑞清
	 * @Date:日期：2016年1月6日 时间：下午5:55:58
	 * @Description: 单个商品下单了
	 * @return boolean
	 * @Version 1.0.0
	 */
	private GenerateOrdersResult insertOrdersSingle(Integer goodsId, Integer normsValueId, Integer buyNum,
			String endAreaCode, Integer periodId, Integer memberId, Integer isActivity, String identifier,
			Integer seckillTimesId, Integer mallType) throws ServiceException {
		TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = transactionManager.getTransaction(definition);
		GenerateOrdersResult generateOrdersResult = new GenerateOrdersResult();
		Integer newOrdersId = null;
		try {
			Map paramMap = new HashMap();
			paramMap.put("goodsId", goodsId);
			paramMap.put("normsValueId", normsValueId);
			Map<String, Object> m = goodsListInterfaceDao.getGoodsNormsValueInfo(paramMap);

			if (m != null) {
				// 获取用户默认收货地址
				ReceivingAddress receivingAddress = receivingAddressInterfaceService
						.selectMemberDefaultAddress(memberId);
				String defaultEndAreaCode = "-1";
				if (receivingAddress != null && Integer.parseInt(receivingAddress.getAreaCode()) > 0) {
					defaultEndAreaCode = receivingAddress.getAreaCode();
				}

				logger.info("defaultEndAreaCode = " + defaultEndAreaCode);
				newOrdersId = insertOrdersList(memberId, endAreaCode, isActivity, identifier, seckillTimesId, mallType);// 生成订单
				ordersFlowInterfaceService.insertOrdersFlow(new GenerateOrdersFlowParams(newOrdersId, memberId, 1));// 新增订单流程
				Integer newOrdersGoodsInfoId = ordersGoodsInfoInterfaceService
						.insertOrdersGoodsInfo(new GenerateOrdersGoodsParams(goodsId, normsValueId, buyNum, newOrdersId,
								memberId, periodId, m.get("sendAddress").toString(), endAreaCode, null, null,
								isActivity, identifier, defaultEndAreaCode, seckillTimesId));// 新增订单商品

				BigDecimal totalLogistics = new BigDecimal(0);

				OrdersGoodsInfo goodsInfo = new OrdersGoodsInfo();
				OrdersList ordersList = new OrdersList();
				goodsInfo.setId(newOrdersGoodsInfoId);
				ordersList.setId(newOrdersId);

				// 订单总金额
				paramMap = new HashMap<>();
				Integer[] goodsIds = new Integer[] { goodsId }, normsValueIds = new Integer[] { normsValueId };
				paramMap.put("goodsIds", goodsIds);
				paramMap.put("normsValueIds", normsValueIds);
				paramMap.put("ordersId", newOrdersId);

				/*
				 * // 活动商品固定运费为广东省8元其它地方12元，ZXXSZS活动不要运费 if (isActivity != null
				 * && isActivity == 1 && StringUtils.isNotEmpty(identifier)) {
				 * if (identifier.contains("CYGHMZS") ||
				 * identifier.contains("CYBK")) { if
				 * (Integer.parseInt(defaultEndAreaCode) < 0 ||
				 * gzcode.equals(defaultEndAreaCode.substring(0, 2))) {
				 * totalLogistics = new BigDecimal(8); } else { totalLogistics =
				 * new BigDecimal(12); } } else if
				 * (identifier.contains("ZXXSZS")) { totalLogistics = new
				 * BigDecimal(0); }
				 * 
				 * goodsInfo.setLogistcsCost(totalLogistics);
				 * ordersGoodsInfoInterfaceDao.updateOrderGoodsInfo(goodsInfo);
				 * 
				 * // 修改订单总金额 BigDecimal totalAmount =
				 * ordersGoodsInfoInterfaceService.getOrdersTotalAmount(paramMap
				 * ); ordersList.setTotalAmount(totalAmount);
				 * ordersList.setSumMoney(totalLogistics.add(totalAmount));
				 * ordersListInterfaceDao.updateOrdersList(ordersList);
				 * 
				 * } else
				 */ {

					// 订单总金额(不包含运费)
					BigDecimal totalAmount = ordersGoodsInfoInterfaceService.getOrdersTotalAmount(paramMap);
					GoodsList goodsList = goodsListInterfaceImplService.queryGoodsListById(goodsId);
					BigDecimal freeMinConsumption = getFreeMinConsumption();

					// 订单总金额小于订单免运费最低消费额，且商品配置了运费模板
					if (freeMinConsumption == null || totalAmount.compareTo(freeMinConsumption) < 0) {
						if (Integer.parseInt(defaultEndAreaCode) > 0 && goodsList.getLogisticsCostId() != null) {
							// 计算商品运费信息
							totalLogistics = ordersGoodsInfoInterfaceDao.getLogisticsCostByAreaCode(defaultEndAreaCode,
									goodsId, goodsList.getLogisticsCostId(), buyNum);
							goodsInfo.setLogistcsCost(totalLogistics);
							ordersGoodsInfoInterfaceDao.updateOrderGoodsInfo(goodsInfo);
						}
					}

					ordersList.setTotalAmount(totalAmount);
					ordersList.setSumMoney(totalAmount.add(totalLogistics));
					ordersListInterfaceDao.updateOrdersList(ordersList);
				}
			}

			transactionManager.commit(status);
			generateOrdersResult.setStatus(true);
			generateOrdersResult.setOrdersIdArray(new Integer[] { newOrdersId });

			return generateOrdersResult;
		} catch (ServiceException | DaoException se) {
			transactionManager.rollback(status);
			throw new ServiceException(se);
		}

	}

	/**
	 * @Title: insertOrdersList
	 * @Author: 王瑞清
	 * @Date:日期：2016年1月5日 时间：上午11:19:05
	 * @Description: 生成订单
	 * @return Integer
	 * @Version 1.0.0
	 */
	private Integer insertOrdersList(Integer memberId, String endAreaCode, Integer isActivity, String identifier,
			Integer seckillTimesId, Integer mallType) throws ServiceException {
		Integer newOrdersId = 0;
		OrdersList ordersList = new OrdersList();
		ordersList.setOrdersNo(GeneratorUtils.generatorOrdersNo("003"));
		ordersList.setStatus(0);// 预下单
		ordersList.setCustomerId(memberId);
		ordersList.setIsActivity((isActivity == null) ? 0 : isActivity);
		ordersList.setIdentifier((identifier == null) ? "" : identifier);
		ordersList.setTotalAmount(new BigDecimal(0));
		ordersList.setSeckillTimesId(seckillTimesId);
		ordersList.setMallType(mallType);
		try {
			ordersListInterfaceDao.insertOrderList(ordersList);
			newOrdersId = ordersList.getId();
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
		return newOrdersId;
	}

	/**
	 * @Package com.sayimo.maker.mall.orders.service.impl
	 * @Author 龚益君
	 * @MethodName:insertOrdersByGoods
	 * @Description:商品详情下单
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2017年2月20日,下午2:00:14
	 */
	public Map<String, Object> insertOrdersByGoods(HttpServletRequest request) throws ServiceException {
		Map<String, Object> rm = new LinkedHashMap<String, Object>();
		Map<String, Object> data = new LinkedHashMap<String, Object>();
		try {
			String goodsId = request.getParameter("goodsId");
			String normValueId = request.getParameter("normsValueId");
			String customerId = request.getAttribute("customerId").toString();
			String buyNum = request.getParameter("buyNum");
			String mallType = request.getParameter("mallType");// 所属商城 1金商城 2银商城
																// 3全返商城 4商企商城
			// String areaCode = request.getParameter("areaCode");
			/*
			 * String isActivityParam = request.getParameter("isActivity");
			 * String identifier = request.getParameter("identifier"); // 活动标识符
			 * // 活动：CYGHMZS_01 // 爆款 // CYBK_01 Integer seckillTimesId =
			 * request.getParameter("seckillTimesId") == null ||
			 * "".equals(request.getParameter("seckillTimesId")) ||
			 * "0".equals(request.getParameter("seckillTimesId")) ? null :
			 * Integer.parseInt(request.getParameter("seckillTimesId"));
			 * areaCode = null == areaCode ? "0" : areaCode; Integer isActivity
			 * = StringUtils.isEmpty(isActivityParam) ? null :
			 * Integer.parseInt(isActivityParam);
			 */
			Integer[] goodsIdArray = { Integer.valueOf(goodsId) };
			Integer[] normsValueArray = { Integer.valueOf(normValueId) };
			Integer[] buyNumArray = { Integer.valueOf(buyNum) };

			GenerateOrdersResult generateOrdersResult = insertOrdersSingle(goodsIdArray[0], normsValueArray[0],
					buyNumArray[0], null, null, Integer.valueOf(customerId), null, null, 0, Integer.valueOf(mallType));

			if (generateOrdersResult.isStatus()) {
				rm.put(Constants.STATUS, Constant.STATUS_SUCCESS);
				data.put("orderId", generateOrdersResult.getOrdersIdArray()[0]);
				rm.put("data", data);
			} else {
				rm.put(Constant.STATUS, Constant.STATUS_ERROR);
				rm.put(Constant.ERROR_CODE, Constant.ORDERS_DOWN_FAIL);
			}
			return rm;
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	/**
	 * @Package com.sayimo.maker.mall.orders.service.impl
	 * @Author 龚益君
	 * @MethodName:insertOrdersByShoopingCart
	 * @Description:购物车下单
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2017年2月20日,下午2:52:59
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> insertOrdersByShoopingCart(HttpServletRequest request) throws ServiceException {
		TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = transactionManager.getTransaction(definition);

		Map<String, Object> rm = new LinkedHashMap<String, Object>();
		Map<String, Object> data = new LinkedHashMap<String, Object>();
		try {
			String shoppingCartIds = request.getParameter("shoppingCartIds");// 购物车ID
			String buyNums = request.getParameter("buyNums");// 购买数量
			String customerId = request.getAttribute("customerId").toString();// 会员ID
			String areaCode = request.getParameter("areaCode");
			String mallType = request.getParameter("mallType");
			areaCode = null == areaCode ? "0" : areaCode; // 地区编码
			Integer[] cartIds = JSONUtil.readValueToBeanArray(shoppingCartIds, Integer.class);
			Integer[] buyNumArray = JSONUtil.readValueToBeanArray(buyNums, Integer.class);
			Integer[] goodsIdArray = new Integer[cartIds.length];
			Integer[] normsValueArray = new Integer[cartIds.length];
			Integer memberId = null;

			if (cartIds.length == buyNumArray.length) {
				// 获取用户默认收货地址
				ReceivingAddress receivingAddress = receivingAddressInterfaceService
						.selectMemberDefaultAddress(Integer.parseInt(customerId));

				Map<Integer, List> providerShoppcartInfoMap = new HashMap<>();

				// 获取所有供应商信息
				List<Object> providerList = goodsListInterfaceImplService
						.queryGoodsListProviderByIds(Arrays.asList(cartIds));
				logger.info("providerList = " + JSONUtil.writeValueAsString(providerList));
				if (CollectionUtils.isNotEmpty(providerList)) {
					for (Object object : providerList) {
						Map<String, Object> map = (Map<String, Object>) object;
						Integer providerId = Integer.parseInt(map.get("providerId").toString());
						logger.info("providerId = " + providerId);
						providerShoppcartInfoMap.put(providerId, new ArrayList<>());
					}
				}

				for (int i = 0; i < cartIds.length; i++) {

					ShoppingCartNormsValue shoppingCartNormsValue = shoppingCartService
							.queryShoppingCartByCartId(cartIds[i], Integer.parseInt(customerId));
					// 如果存在已经下单的商品，再次下单直接返回下单失败
					if (shoppingCartNormsValue == null) {
						rm.put(Constant.STATUS, Constant.STATUS_ERROR);
						rm.put(Constant.ERROR_CODE, Constant.ORDERS_DOWN_FAIL);
						return rm;
					}
					goodsIdArray[i] = shoppingCartNormsValue.getGoodsId();
					normsValueArray[i] = shoppingCartNormsValue.getNormsValueId();

					// 供应商对应的商品信息
					GoodsList goodsList = goodsListInterfaceImplService
							.queryGoodsListById(shoppingCartNormsValue.getGoodsId());
					if (goodsList.getStatus() - 1 != 0) {
						Map<String, Object> map = new HashMap<>();
						rm.put(Constant.STATUS, Constant.STATUS_ERROR);
						rm.put(Constant.ERROR_CODE, map.put(Constant.MSG, "该商品未上架"));
						return rm;
					}
					Map<String, Object> providerGoodsInfoMap = new HashMap<>();
					providerGoodsInfoMap.put("cartId", cartIds[i]);
					providerGoodsInfoMap.put("goodsId", shoppingCartNormsValue.getGoodsId());
					providerGoodsInfoMap.put("normsValueId", shoppingCartNormsValue.getNormsValueId());
					providerGoodsInfoMap.put("buyNum", buyNumArray[i]);
					providerGoodsInfoMap.put("sendAddress", goodsList.getSendAddress());
					providerGoodsInfoMap.put("logisticsCostId", goodsList.getLogisticsCostId());

					logger.info("goodsList.providerId = " + goodsList.getProviderId());
					providerShoppcartInfoMap.get(goodsList.getProviderId()).add(providerGoodsInfoMap);

					if (memberId == null) {
						memberId = shoppingCartNormsValue.getCustomerId();
					}
				}
				MessageObject mo = insertOrdersGoodsInfoByShoppingCart(memberId, areaCode, Integer.valueOf(mallType),
						providerShoppcartInfoMap, receivingAddress);
				if (mo.getKey().equals(Constants.SUCCESS)) {
					rm.put(Constants.STATUS, Constant.STATUS_SUCCESS);
					Integer[] ordersIdArray = (Integer[]) mo.getObject();
					data.put("orderId", ordersIdArray);
					rm.put("data", data);
				} else {
					rm.put(Constant.STATUS, Constant.STATUS_ERROR);
					rm.put(Constant.ERROR_CODE, (String) mo.getObject());
				}

				transactionManager.commit(status);
			} else {
				rm.put(Constant.STATUS, Constant.STATUS_ERROR);
				rm.put(Constant.ERROR_CODE, Constant.ORDERS_DOWN_FAIL);
			}
			return rm;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			transactionManager.rollback(status);
			throw new ServiceException(e);
		}
	}

	/**
	 * @package com.sayimo.school.mall.module.order.service.impl
	 * @author chenpy
	 * @Title:
	 * @Description:
	 * @param
	 * @throws @return
	 *             MessageObject
	 * @date 2016年6月30日
	 */
	@SuppressWarnings("unchecked")
	private MessageObject insertOrdersGoodsInfoByShoppingCart(Integer memberId, String areaCode, Integer mallType,
			Map<Integer, List> providerShoppcartInfoMap, ReceivingAddress receivingAddress) throws ServiceException {
		MessageObject messageObject = new MessageObject();

		Integer ordersIds[] = new Integer[0];
		Set<Integer> providerIds = providerShoppcartInfoMap.keySet();
		if (CollectionUtils.isNotEmpty(providerIds)) {
			String defaultEndAreaCode = null;
			if (receivingAddress != null && StringUtils.isNotBlank(receivingAddress.getAreaCode())) {
				defaultEndAreaCode = receivingAddress.getAreaCode();
			}
			logger.info("defaultEndAreaCode = " + defaultEndAreaCode);

			for (Integer providerId : providerIds) {
				// 生成订单
				Integer ordersId = insertOrdersList(memberId, areaCode, null, null, null, mallType);// 生成订单
				// 新增订单流程
				ordersFlowInterfaceService.insertOrdersFlow(new GenerateOrdersFlowParams(ordersId, memberId, 1));
				ordersIds = (Integer[]) ArrayUtils.add(ordersIds, ordersId);

				// 生成对应的商品信息
				List providerGoodsInfos = providerShoppcartInfoMap.get(providerId);
				List<OrdersGoodsInfo> goodsInfos = new ArrayList<>();
				List goodsInfoMaps = new ArrayList();

				for (Object object : providerGoodsInfos) {
					Map<String, Object> providerGoodsMap = (Map<String, Object>) object;
					Integer goodsId = Integer.parseInt(providerGoodsMap.get("goodsId").toString());
					Integer normsValueId = Integer.parseInt(providerGoodsMap.get("normsValueId").toString());
					Integer buyNum = Integer.parseInt(providerGoodsMap.get("buyNum").toString());
					String sendAddress = providerGoodsMap.get("sendAddress") != null
							? providerGoodsMap.get("sendAddress").toString() : "";
					Integer logisticsCostId = providerGoodsMap.get("logisticsCostId") != null
							? Integer.parseInt(providerGoodsMap.get("logisticsCostId").toString()) : null;
					Integer cartId = Integer.parseInt(providerGoodsMap.get("cartId").toString());
					int newGoodsInfoId = ordersGoodsInfoInterfaceService
							.insertOrdersGoodsInfo(new GenerateOrdersGoodsParams(goodsId, normsValueId, buyNum,
									ordersId, memberId, null, sendAddress, areaCode, logisticsCostId, cartId, null,
									null, defaultEndAreaCode, null));

					Map ordersGoodsInfoMap = new HashMap();
					ordersGoodsInfoMap.put("id", newGoodsInfoId);
					ordersGoodsInfoMap.put("goodsId", goodsId);
					ordersGoodsInfoMap.put("normsValueId", normsValueId);
					goodsInfoMaps.add(ordersGoodsInfoMap);
				}

				// 计算运费
				OrdersList ordersList = new OrdersList();
				ordersList.setId(ordersId);
				setOrdersSumAmount(goodsInfoMaps, ordersList, defaultEndAreaCode);
			}
		}

		messageObject.setKey(Constant.SUCCESS);
		messageObject.setObject(ordersIds);
		return messageObject;
	}

	/**
	 * @Title: ordersDetails
	 * @Author: 王瑞清
	 * @Date:日期：2016年1月5日 时间：上午11:19:05
	 * @Description: 查询订单详情信息
	 * @return Integer
	 * @Version 1.0.0
	 */
	private Map<String, Object> ordersDetails(String orderIds, Integer customerId, String statusType)
			throws ServiceException {
		Map<String, Object> rm = new LinkedHashMap<String, Object>();
		Map<String, Object> data = new LinkedHashMap<String, Object>();

		try {
			Integer[] orderIdArray = JSONUtil.readValueToBeanArray(orderIds, Integer.class);
			logger.info("orderIdArray = " + orderIdArray);

			// 获取订单统计信息
			Integer orderTotal = queryOrdersListTotal(Arrays.asList(orderIdArray));
			// 订单总金额（含运费）
			Double ordersTotalMoney = orderTotalMoney(orderIdArray);
			// 订单总运费
			BigDecimal kogistcsCostTotal = orderLogistcsCost(orderIdArray);
			// 生成订单地址信息
			GenerateReceivingAddressResult generateReceivingAddressResult = ordersReceivingAddressInterfaceService
					.insertOrdersReceivingBatchCode(orderIdArray, customerId);

			Map<String, Object> receiveMap = new LinkedHashMap<String, Object>();
			receiveMap.put("receiveAddress", StringUtils.isEmpty(generateReceivingAddressResult.getPlaceAddress()) ? ""
					: generateReceivingAddressResult.getPlaceAddress());
			receiveMap.put("linkInformation", StringUtils.isEmpty(generateReceivingAddressResult.getLinkInformation())
					? "" : generateReceivingAddressResult.getLinkInformation());
			receiveMap.put("receivePeople", (StringUtils.isEmpty(generateReceivingAddressResult.getReceivePeople()))
					? "" : generateReceivingAddressResult.getReceivePeople());
			receiveMap.put("isSchool", generateReceivingAddressResult.getIsSchool() == null ? 0
					: generateReceivingAddressResult.getIsSchool());
			receiveMap.put("batchCode", generateReceivingAddressResult.getBatchCode());

			List<Object> orderList = new ArrayList<Object>();

			List<OrdersList> ordersLists = ordersListInterfaceDao.queryOrdersByIds(Arrays.asList(orderIdArray));
			List infoList = ordersGoodsInfoInterfaceService.queryOrdersGoodsInfoByOrderId(ordersLists.get(0).getId());
			Map<String, Object> infoMap = (Map) infoList.get(0);
			Map<String, Object> providerMap = new HashMap<>();
			providerMap.put("providerName", infoMap.get("providerName"));
			providerMap.put("providerLinkInfo", infoMap.get("mobilePhone"));
			providerMap.put("providerAddress", infoMap.get("providerAddress"));
			for (OrdersList ordersList : ordersLists) {
				Map<String, Object> orderInfo = new LinkedHashMap<String, Object>();
				List<Object> goodsList = new ArrayList<Object>();
				orderInfo.put("ordersId", ordersList.getId());
				orderInfo.put("isActivity", ordersList.getIsActivity());
				orderInfo.put("identifier", ordersList.getIdentifier());
				orderInfo.put("ordersNo", ordersList.getOrdersNo());
				orderInfo.put("status", ordersList.getStatus());
				orderInfo.put("payMode", ordersList.getPayMode());
				orderInfo.put("leaveWords", ordersList.getLeaveWords());

				String isActivity = ordersList.getIsActivity() == null ? null : ordersList.getIsActivity().toString();
				String identifier = ordersList.getIdentifier();
				Integer seckillTimesId = ordersList.getSeckillTimesId();

				/*
				 * if (isActivity != null && !isActivity.equals("") &&
				 * isActivity.equals("1") && identifier != null &&
				 * !identifier.equals("") && (identifier.contains("PT_SPMQ"))) {
				 * orderInfo.put("seckillTimesId",
				 * StringUtil.nullReplace(ordersList.getSeckillTimesId())); //
				 * 获取当前秒抢活动时间段信息 Map<String, Object> actTimesMap =
				 * this.baseSeckillTimesDao.selectBaseSeckillTimesByNow(
				 * identifier, ordersList.getSeckillTimesId()); // 秒抢活动限购
				 * orderInfo.put("seckillStartDate",
				 * StringUtil.nullReplace(Long.parseLong(actTimesMap.get(
				 * "startDate").toString()))); orderInfo.put("seckillEndDate",
				 * StringUtil.nullReplace(Long.parseLong(actTimesMap.get(
				 * "endDate").toString()))); } else if (isActivity != null &&
				 * !isActivity.equals("") && isActivity.equals("1") &&
				 * identifier != null && !identifier.equals("") &&
				 * (identifier.contains("PT_TG_"))) { Map<String, Object>
				 * dataMap = new HashMap<>(); dataMap =
				 * baseGroupBuyDao.queryInfoByIdentifierGoods(identifier);
				 * 
				 * Integer alreadyBuy = (Integer) dataMap.get("number") -
				 * (Integer) dataMap.get("stock"); orderInfo.put("alreadyBuy",
				 * alreadyBuy); orderInfo.put("number", (Integer)
				 * dataMap.get("number")); orderInfo.put("startDate",
				 * dataMap.get("startDate")); orderInfo.put("endDate",
				 * dataMap.get("endDate")); }
				 */
				List<OrdersGoodsNormsInfo> ordersGoodsNormsInfos = ordersGoodsNormsInfoInterfaceService
						.queryOrdersGoodsNormsInfoByOrdersId(statusType, ordersList.getId(),
								Integer.valueOf(customerId));
				for (OrdersGoodsNormsInfo ordersGoodsNormsInfo : ordersGoodsNormsInfos) {

					Map<String, Object> goodsInfoMap = new LinkedHashMap<String, Object>();
					goodsInfoMap.put("isTurnBack", ordersGoodsNormsInfo.getIsTurnBack());
					Integer goodsId = ordersGoodsNormsInfo.getGoodsId();
					Map<String, Object> goodsComment = new HashMap<>();
					goodsComment.put("ordersId", ordersList.getId());
					goodsComment.put("goodsId", ordersGoodsNormsInfo.getGoodsId());
					Integer count = goodsCommentInterfaceImplDao.getCommentCount(goodsComment);
					if (count > 0) {
						goodsInfoMap.put("canComment", 0);
					} else {
						goodsInfoMap.put("canComment", 1);
					}
					goodsInfoMap.put("goodsName", ordersGoodsNormsInfo.getGoodsName());
					goodsInfoMap.put("sendAddress", ordersGoodsNormsInfo.getSendAddress());
					goodsInfoMap.put("photoUrl", ordersGoodsNormsInfo.getPhotoPath());
					goodsInfoMap.put("id", ordersGoodsNormsInfo.getGoodsId());
					goodsInfoMap.put("normsValueId", ordersGoodsNormsInfo.getNormsValueId());
					goodsInfoMap.put("normsValues", getNormsValueString(ordersGoodsNormsInfo.getNormsValueIds()));
					goodsInfoMap.put("buyNum", ordersGoodsNormsInfo.getBuyNum());
					goodsInfoMap.put("canReturnGoodsNum", ordersGoodsNormsInfo.getBuyNum());
					goodsInfoMap.put("sellPrice", ordersGoodsNormsInfo.getSellPrice());
					goodsInfoMap.put("status", 1);

					/*
					 * if (isActivity != null && !isActivity.equals("") &&
					 * isActivity.equals("1")) { // 如果为秒抢活动 if (identifier !=
					 * null && !identifier.equals("") &&
					 * (identifier.contains("PT_SPMQ"))) { // 获取秒抢活动商品信息
					 * Map<String, Object> activityGoodsMap =
					 * this.baseSeckillGoodsDao
					 * .querySeckillGoodsInfoByGoodsId(goodsId, identifier,
					 * seckillTimesId); // 活动商品名称 goodsInfoMap.put("goodsName",
					 * activityGoodsMap.get("goodsName")); } else if (identifier
					 * != null && !identifier.equals("") &&
					 * (identifier.contains("PT_KJ"))) { // 获取砍价活动信息 Map cutMap
					 * = new HashMap(); cutMap.put("identifier", identifier);
					 * List<BaseCut> CutList = new ArrayList<BaseCut>(); CutList
					 * = baseCutDao.selectBaseCutByIdentifier(cutMap);
					 * 
					 * // 活动商品名称 goodsInfoMap.put("goodsName",
					 * CutList.get(0).getGoodsName()); } else if (identifier !=
					 * null && !identifier.equals("") &&
					 * (identifier.contains("PT_TG_"))) { // 如果为团购活动
					 * 
					 * // 获取团购活动信息 Map<String, Object> actMap =
					 * this.baseGroupBuyDao.selectBaseGroupBuyIdentifier(
					 * identifier); // 活动商品名称 goodsInfoMap.put("goodsName",
					 * actMap.get("goodsName")); } else { // 获取活动商品信息
					 * Map<String, Object> activityGoodsMap =
					 * goodsListInterfaceDao
					 * .queryActivityGoodsInfoByGoodsId(goodsId, identifier); //
					 * 活动商品名称 goodsInfoMap.put("goodsName",
					 * activityGoodsMap.get("goodsName")); } }
					 */

					String isTurnBack = ordersGoodsNormsInfo.getIsTurnBack();

					// ① 判断该商品是否还可以进行退换货申请
					{
						// 商品不支持退换货
						if (!isTurnBack.equals("Y")) {
							goodsInfoMap.put("status", 2);
						}

						// 判断已申请待审核的退换货订单
						/*
						 * Map<String, Integer> paramMap = new HashMap<>();
						 * paramMap.put("ordersId", ordersList.getId());
						 * paramMap.put("goodsId",
						 * ordersGoodsNormsInfo.getGoodsId()); Integer
						 * sumReturnGoods =
						 * ordersListInterfaceDao.getReturnGoodsNumInOrder(
						 * paramMap);
						 * 
						 * if (ordersGoodsNormsInfo.getBuyNum() - sumReturnGoods
						 * < 1) { goodsInfoMap.put("status", 2); }
						 * goodsInfoMap.put("canReturnGoodsNum",
						 * ordersGoodsNormsInfo.getBuyNum() - sumReturnGoods);
						 */
					}
					// ① end

					// goodsInfoMap.put("isTurnBack",
					// ordersGoodsNormsInfo.getIsTurnBack());

					// if (ordersList.getIsActivity() != null &&
					// ordersList.getIsActivity() == 1
					// && ordersList.getIdentifier() != null &&
					// ordersList.getIdentifier().contains("CYGHMZS")) {
					// goodsInfoMap.put("transactionPrice", 0);
					// } else {
					goodsInfoMap.put("transactionPrice", ordersGoodsNormsInfo.getTransactionPrice());
					// }
					goodsInfoMap.put("logisticsCost", ordersGoodsNormsInfo.getLogistcsCost().doubleValue());

					goodsList.add(goodsInfoMap);
				}
				orderInfo.put("goodsList", goodsList);
				orderList.add(orderInfo);
			}
			Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(customerId);
			// 组装数据
			data.put("walletBalance", wallet == null ? null : wallet.getRemainingSilverScore());
			data.put("ordersTotalMoney", ordersTotalMoney);
			data.put("logisticsCostTotal", kogistcsCostTotal.doubleValue());
			data.put("orderNum", orderTotal);
			data.put("receiveInfo", receiveMap);
			data.put("providerInfo", providerMap);
			logger.info("receiveInfo = " + JSONUtil.writeValueAsString(receiveMap));
			data.put("orderList", orderList);
			rm.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			rm.put(Constant.DATA, data);

			logger.info("rm = " + JSONUtil.writeValueAsString(rm));
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return rm;
	}

	/**
	 * @Title: queryMemberCustomerOrderList
	 * @Author: 曹频辉
	 * @Date:日期：2016年1月6日 时间：上午11:36:05
	 * @Description: 查询用户指定状态的订单列表
	 * @param customerId
	 * @param status
	 * @return Map
	 * @Version 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Map editMemberCustomerOrderList(Integer customerId, Integer status, Integer pageSize, Integer pageNow,
			Integer mallType, Integer orderType) throws ServiceException {
		Map map = new HashMap();
		try {
			List<Map> orderList = new ArrayList<>();
			if (orderType - 1 == 0) {
				orderList = ordersListInterfaceDao.getOrderListByCustomerId(customerId, status, pageSize,
						(pageNow - 1) * pageSize, mallType);
			} else {
				Customer customer = new Customer();
				customer.setId(customerId);
				List<Customer> customers = customerInterfaceImplService.queryCustomerByCond(customer);
				orderList = ordersListInterfaceDao.getOrderListByProviderId(customers.get(0).getProviderRefId(), status,
						mallType, pageSize, (pageNow - 1) * pageSize);
			}
			logger.info("orderList = " + JSONUtil.writeValueAsString(orderList));
			if (CollectionUtils.isEmpty(orderList)) {
				Map orderMap = new HashMap();
				orderMap.put("orderList", orderList);
				map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				map.put(Constant.DATA, orderMap);
				return map;
			}

			for (Iterator iterator = orderList.iterator(); iterator.hasNext();) {
				Map map2 = (Map) iterator.next();
				Integer ordersId = (Integer) map2.get("ordersId");
				// 更新订单状态
				Map<String, Object> parmMap = new HashMap<String, Object>();
				Integer goodsCount = ordersGoodsInfoInterfaceDao.queryCountByOrderId((Integer) map2.get("ordersId"));
				map2.remove("actionDate");
				Integer isSchool = (Integer) map2.get("isSchool"), isActivity = (Integer) map2.get("isActivity");
				if (isSchool == null) {
					map2.put("isSchool", "");
				} else {
					map2.put("isSchool", isSchool);
				}
				if (isActivity == null) {
					map2.put("isActivity", "");
				} else {
					map2.put("isActivity", isActivity);
				}
				String identifier = (String) map2.get("identifier");
				if (identifier == null) {
					map2.put("identifier", "");
				} else {
					map2.put("identifier", identifier);
				}

				BigDecimal kogistcsCostTotal = new BigDecimal(0);
				kogistcsCostTotal = orderLogistcsCost(new Integer[] { (Integer) map2.get("ordersId") });
				map2.put("logistcsCost", kogistcsCostTotal);

				if (map2.get("sumMoney") == null) {
					map2.put("sumMoney", "");
				} else {
					map2.put("totalAmount", map2.get("sumMoney"));
				}

				List goodsList = ordersListInterfaceDao.getGoodsListByOrdersId((Integer) map2.get("ordersId"));
				logger.info("goodsList === " + JSONUtil.writeValueAsString(goodsList));
				int goodsLength = 0;
				if (goodsList != null && goodsList.size() > 0) {
					goodsLength = goodsList.size();
					logger.info("goodsLength = " + goodsLength);
					for (Iterator goodsListIterator = goodsList.iterator(); goodsListIterator.hasNext();) {
						Map goodsTempMap = (Map) goodsListIterator.next();
						Integer goodsId = (Integer) goodsTempMap.get("id");
						if (goodsTempMap.get("normsValueId") == null) {
							goodsTempMap.put("normsValueId", "");
						}
						if (goodsTempMap.get("id") == null) {
							goodsTempMap.put("id", "");
						}
						if (goodsTempMap.get("buyNum") == null) {
							goodsTempMap.put("buyNum", "");
						}
						if (goodsTempMap.get("sellPrice") == null) {
							goodsTempMap.put("sellPrice", "");
						}

						if (goodsTempMap.get("transactionPrice") == null) {
							goodsTempMap.put("transactionPrice", "");
						}
						if (goodsTempMap.get("goodsName") == null) {
							goodsTempMap.put("goodsName", "");
						}
						if (goodsTempMap.get("photoUrl") == null) {
							goodsTempMap.put("photoUrl", "");
						}
						goodsTempMap.put("status", 1);

						// ① 判断该商品是否还可以进行退换货申请
						{
							String isTurnBack = String.valueOf(goodsTempMap.get("isTurnBack"));
							// 退换货待审核，或者商品数量为0时
							int buyNum = Integer.parseInt(goodsTempMap.get("buyNum").toString());
							if (buyNum < 1) {
								goodsListIterator.remove();
								goodsLength -= 1;
								continue;
							}
							if (!isTurnBack.equals("Y")) {
								goodsTempMap.put("isTurnBack", 2);
							}

							/*
							 * // 判断已申请待审核的退换货订单 Map<String, Integer> paramMap =
							 * new HashMap<>(); paramMap.put("ordersId",
							 * ordersId); paramMap.put("goodsId", goodsId);
							 * Integer sumReturnGoods =
							 * ordersListInterfaceDao.getReturnGoodsNumInOrder(
							 * paramMap); // 该商品全部申请了退换货 if (buyNum -
							 * sumReturnGoods < 1) { goodsTempMap.put("status",
							 * 2); }
							 */
						}
						// ① end

						String normsValueIds = (String) goodsTempMap.get("normsValueIds");
						String normsValues = getNormsValueString(normsValueIds);

						goodsTempMap.put("canComment", 0);
						// 商品可评论
						if (goodsTempMap.get("commentContent") == null) {
							goodsTempMap.put("canComment", 1);
						}
					}

					map2.put("goodsList", goodsList);

				} else if (goodsList != null && goodsList.size() == 0) {
					map.put(Constant.STATUS, Constant.STATUS_ERROR);
					map.put(Constant.ERROR_CODE, Constant.SYSTEM_NO_DATA);
					return map;
				} else {
					map.put(Constant.STATUS, Constant.STATUS_ERROR);
					map.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
					return map;
				}

				logger.info("goodsLength = " + goodsLength);
				if (goodsLength == 0) {
					iterator.remove();
				}
			}

			Map orderListMap = new HashMap();
			orderListMap.put("orderList", orderList);
			map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			map.put(Constant.DATA, orderListMap);
			logger.info("resultMap = " + JSONUtil.writeValueAsString(map));

			return map;

		} catch (DaoException de) {
			logger.error(de);
			throw new ServiceException(de);
		}

	}

	public Integer queryOrdersListTotal(List<Integer> ids) throws ServiceException {
		try {
			return ordersListInterfaceDao.queryOrdersListTotal(ids);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
	}

	/**
	 * @Title: payOrder
	 * @Author: chenpy
	 * @Date:日期：2016年1月8日 时间：下午2:05
	 * @Description: 订单支付
	 * @return String
	 * @throws Exception
	 * @throws @Version
	 *             1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map updatePayOrder(HttpServletRequest request) throws Exception {

		Map resultMap = new HashMap();
		String orderIds = request.getParameter("orderIds");
		logger.info("orderIds = " + orderIds);
		String applyType = request.getParameter("applyType");// "WEB/APP/WAP/PC"
		String payMoney = request.getParameter("payMoney");
		String payType = request.getParameter("payType");
		String customerId = request.getParameter("customerId");
		String leaveWords = request.getParameter("leaveWords");
		String password = request.getParameter("password") == null ? null
				: Base64Utils.decodeBase64(request.getParameter("password"));
		String areaCode = request.getParameter("areaCode");

		// 数据验证
		Double amounts = 0.00;

		Map payOrderMap = validPayOrder(orderIds, payMoney, payType, customerId, password, amounts, areaCode);
		if (!Constant.STATUS_SUCCESS.equals(payOrderMap.get(Constant.STATUS))) {
			return payOrderMap;
		}
		payOrderMap.remove(Constant.STATUS);
		Integer[] orderIdArray = JSONUtil.readValueToBeanArray(orderIds, Integer.class);

		List<Integer> cartIdList = new ArrayList<Integer>();
		List<OrdersGoodsInfo> ordersGoodsInfos = null;
		for (Integer ordersId : orderIdArray) {
			OrdersList ordersList = queryOrdersListById(ordersId);
			if (ordersList != null) {
				if (0 == ordersList.getStatus()) {
					ordersGoodsInfos = ordersGoodsInfoInterfaceService.queryOrdersGoodsInfoByOrdersId(ordersId);
					for (OrdersGoodsInfo ordersGoodsInfo : ordersGoodsInfos) {
						if (null != ordersGoodsInfo.getCartId()) {
							cartIdList.add(ordersGoodsInfo.getCartId());
						}
					}
				}
			}
		}

		TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = transactionManager.getTransaction(definition);
		try {
			// 将已下单的更改为已下单
			for (Integer orderId : orderIdArray) {

				logger.info("resultMap:" + resultMap);

				if (resultMap.size() > 0) {
					if (resultMap.get(Constant.STATUS).toString().equals(Constant.STATUS_ERROR)) {
						return resultMap;
					}
				}

				updateOrdersListStatus(1, orderId);
			}

			// 删除购物车
			if (cartIdList.size() > 0) {
				shoppingCartService.deleteShoppingCartByIds(cartIdList);
			}

			transactionManager.commit(status);

			String orderIdJoin = "";
			List<OrdersList> ordersLists = new ArrayList<OrdersList>();
			ordersLists = ordersListInterfaceDao.queryOrdersByIds(Arrays.asList(orderIdArray));
			if (!CollectionUtils.isEmpty(ordersLists)) {
				orderIdJoin = ordersLists.get(0).getOrdersNo();
			}
			List<GoodsList> goodsLists = goodsListInterfaceImplService
					.selectGoodsInfoByOrdersIds(Arrays.asList(orderIdArray));
			String goodName = goodsLists.get(0).getGoodsName();
			Integer goodsId = goodsLists.get(0).getId();
			if (goodName.length() >= 8) {
				goodName = goodName.substring(0, 8);
			}
			payOrderMap.put("customerId", customerId);
			payOrderMap.put("payMoney", payMoney);
			payOrderMap.put("orderIds", orderIds);
			payOrderMap.put("ordersNo", orderIdJoin);
			payOrderMap.put("amounts", amounts);
			payOrderMap.put("areaCode", areaCode);
			payOrderMap.put("goodsName", goodName + "...");
			payOrderMap.put("leaveWords", leaveWords);
			// 判断支付方式

			if (payType.equals("0")) { // 钱包支付(银积分支付)
				payOrderMap.put("payModel", "sayimoPay");
				return paySuccess(payOrderMap);
			}
			if (payType.equals("3")) { // 钱包支付(现金支付)
				payOrderMap.put("payModel", "sayimoPayCash");
				return paySuccess(payOrderMap);
			} else {
				Double payPrice = Double.parseDouble(payMoney);
				payPrice = payPrice - amounts;
				if (payPrice <= 0) {
					if (payType.equals("1")) {
						payOrderMap.put("payModel", "weChatPay");
					} else {
						payOrderMap.put("payModel", "aliPay");
					}
					return paySuccess(payOrderMap);
				}

				payOrderMap.put("applyType", applyType);
				if (payType.equals("1")) { // 微信支付
					if (applyType.equals("APP")) {
						payOrderMap.put("payPrice", payPrice);
						payOrderMap.put("_customerId", customerId);
						payOrderMap.put("_ordersType", 3);
						payOrderMap.put("_payPrice", payPrice);
						payOrderMap.put("_orderIds", orderIds);
						logger.info("payOrderMap ==== " + payOrderMap);
						resultMap = WXPay.wxPayOrder(payOrderMap, request);
					} else if (applyType.equals("WEB")) {
						payOrderMap.put("payPrice", payPrice);
						logger.info("payOrderMap ==== " + payOrderMap);
						resultMap = wxPayOrder(payOrderMap, request);
					} else if (applyType.equals("PC")) {
						payOrderMap.put("payPrice", payPrice);
						payOrderMap.put("_customerId", customerId);
						payOrderMap.put("_ordersType", 3);
						payOrderMap.put("_payPrice", payPrice);
						payOrderMap.put("_orderIds", orderIds);
						payOrderMap.put("payPrice", payPrice);
						logger.info("payOrderMap ==== " + payOrderMap);
						resultMap = WXScanCodePay.weixin_pay(payOrderMap, request);
					} else if (applyType.equals("WAP")) {
						payOrderMap.put("payPrice", payPrice);
						payOrderMap.put("_customerId", customerId);
						payOrderMap.put("_ordersType", 3);
						payOrderMap.put("_payPrice", payPrice);
						payOrderMap.put("_orderIds", orderIds);
						logger.info("payOrderMap ==== " + payOrderMap);
						resultMap = WXPay.wxPayOrder(payOrderMap, request);
					}
				} else { // 支付宝支付
					if (applyType.equals("APP")) {
						payOrderMap.put("payPrice", payPrice);
						payOrderMap.put("_customerId", customerId);
						payOrderMap.put("_ordersType", 3);
						payOrderMap.put("_payPrice", payPrice);
						payOrderMap.put("_orderIds", orderIds);
						logger.info("payOrderMap ==== " + payOrderMap);
						resultMap = ALiPay.aliPayOrder(payOrderMap);
					} else if (applyType.equals("WAP")) { // 手机网站支付
						payOrderMap.put("payPrice", payPrice);
						payOrderMap.put("_customerId", customerId);
						payOrderMap.put("_ordersType", 3);
						payOrderMap.put("_payPrice", payPrice);
						payOrderMap.put("_orderIds", orderIds);
						logger.info("payOrderMap ==== " + payOrderMap);
						resultMap = AliWapPay.aliWapPayOrder(payOrderMap);
					} else if (applyType.equals("PC")) { // 电脑网站支付
						payOrderMap.put("payPrice", payPrice);
						payOrderMap.put("_customerId", customerId);
						payOrderMap.put("_ordersType", 3);
						payOrderMap.put("_payPrice", payPrice);
						payOrderMap.put("_orderIds", orderIds);
						logger.info("payOrderMap ==== " + payOrderMap);
						resultMap = AliScancodePay.creatOrCode(payOrderMap);
					}
				}

			}

		} catch (Exception e) {
			transactionManager.rollback(status);
			logger.error(e);
			throw new ServiceException(e);
		}

		return resultMap;

	}

	/**
	 * 
	 * @MethodName validPayOrder
	 * @Description 订单支付验证前进行数据校验
	 * 
	 * @author chenpy
	 * @date 2016年1月8日 下午2:53:11
	 * @param
	 * @return Map
	 * @throws DaoException
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private Map validPayOrder(String orderIds, String payMoney, String payType, String customerId, String password,
			Double amounts, String areaCode) throws ServiceException, DaoException {
		Map resultMap = new HashMap();

		Integer[] orderIdArray = null;
		orderIdArray = JSONUtil.readValueToBeanArray(orderIds, Integer.class);

		logger.info("orderIds = " + orderIds + ", payMoney = " + payMoney + ", payType = " + payType + ", customerId = "
				+ customerId + ", password = " + password + ", areaCode = " + areaCode);
		// 参数异常
		if (StringUtils.isEmpty(orderIds) || StringUtils.isEmpty(payMoney) || StringUtils.isEmpty(payType)
				|| StringUtils.isEmpty(customerId)) {
			logger.error("params error");
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}

		logger.info(StringUtils.isEmpty(password));
		// 钱包支付
		if (payType.equals("0") || payType.equals("3")) {
			if (StringUtils.isEmpty(password)) {
				logger.error("param password is null");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.WALLET_PASSWORD_IS_NULL);
				return resultMap;
			}

			Wallet memberWallet = walletInterfaceImplService.queryWalletByCustomerId(Integer.parseInt(customerId));

			if (StringUtils.isEmpty(memberWallet.getPassWord())) { // 用户没有设置提现密码
				logger.error("wallet password is not installed");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.WALLET_PASSWORD_IS_NOT_INSTALLED);
				return resultMap;
			}
			logger.info("wallet password" + memberWallet.getPassWord());
			String Md5password = null;
			try {
				Md5password = MD5Util.MD5Encode(CbcEncrypt.encrypt(password), "UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!memberWallet.getPassWord().equals(Md5password)) { // 提现密码错误
				logger.error("wallet password error");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.WALLET_PASSWORD_ERROR);
				return resultMap;
			}
		}

		// 当前没有订单
		List<OrdersList> ordersLists = ordersListInterfaceDao.queryOrdersByIds(Arrays.asList(orderIdArray));
		if (CollectionUtils.isEmpty(ordersLists) || ordersLists.size() != orderIdArray.length) {
			logger.error("ordersLists is null");
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			return resultMap;
		}

		// 验证收货地址
		List<OrdersReceivingAddress> addresses = ordersReceivingAddressInterfaceService
				.queryOrderReceivingCountByOrdersIds(Arrays.asList(orderIdArray));
		if (CollectionUtils.isEmpty(addresses) || StringUtils.isEmpty(addresses.get(0).getReceivingPeople())
				|| StringUtils.isEmpty(addresses.get(0).getAddress())) { // 订单收货地址为空
			logger.error("recevingAddress is null");
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_RECEVING_ADDRESS_ISNULL);
			return resultMap;
		}

		// 该订单已支付
		for (OrdersList ordersList : ordersLists) {
			if (ordersList.getStatus() > 1) {
				logger.error("ordersLists is paid");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_LIST_IS_PAID);
				return resultMap;
			}
		}

		// 验证支付金额
		Integer[] ordersIds = new Integer[ordersLists.size()];
		for (int i = 0; i < ordersIds.length; i++) {
			ordersIds[i] = ordersLists.get(i).getId();
		}
		Double ordersTotalMoney = orderTotalMoney(ordersIds);
		// 订单支付总金额被篡改
		if (Double.compare(Double.valueOf(payMoney), ordersTotalMoney) != 0) {
			logger.error("orders total money is falsified");
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_TOTAL_MONEY_IS_FALSIFIED);
			return resultMap;
		}

		// 判断商品是否支持发货到指定发货地址
		areaCode = addresses.get(0).getAreaCode();
		Map<String, Object> paramMap = new HashMap<>();
		if (Integer.parseInt(areaCode) > 0) {
			paramMap.put("areaCode", areaCode);
			paramMap.put("ordersIds", ordersIds);
			List goodsLogistics = goodsNormsValueStockInterfaceDao.queryOrdersLogistics(paramMap);
			if (CollectionUtils.isNotEmpty(goodsLogistics)) {
				for (Object object : goodsLogistics) {
					Map m = (Map) object;
					if (m.get("isFreight") != null && m.get("isFreight").toString().equals("Y")
							&& m.get("areaCodeList") == null) {
						logger.info("此地区暂时不支持发货");
						resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
						resultMap.put(Constant.ERROR_CODE, Constant.ADDRESS_CANT_SHIP);
						logger.info("resultMap = " + JSONUtil.writeValueAsString(resultMap));
						return resultMap;
					}
				}
			}
		}

		/*
		 * // 判断活动商品库存 if (ordersLists.size() == 1) { OrdersList ordersList =
		 * ordersLists.get(0); // 订单商品是活动商品 if (ordersList.getIsActivity() == 1)
		 * { paramMap = new HashMap<>(); paramMap.put("ordersId",
		 * ordersList.getId()); paramMap.put("identifier",
		 * ordersList.getIdentifier()); Map<String, Object> activitiesGoodsMap =
		 * new HashMap<String, Object>(); if
		 * (ordersList.getIdentifier().contains("PT_SPMQ")) { // 秒抢
		 * activitiesGoodsMap =
		 * goodsNormsValueStockInterfaceDao.getSeckillStockNum(paramMap); } if
		 * (ordersList.getIdentifier().contains("PT_KJ")) { // 砍价
		 * activitiesGoodsMap =
		 * goodsNormsValueStockInterfaceDao.getCutPriceStockNum(paramMap); }
		 * else if (ordersList.getIdentifier().contains("PT_TG_")) { // 团购
		 * activitiesGoodsMap =
		 * goodsNormsValueStockInterfaceDao.getGroupBuyStockNum(paramMap); }
		 * else { activitiesGoodsMap =
		 * goodsNormsValueStockInterfaceDao.getActivityStockNum(paramMap); }
		 * 
		 * logger.info("activitiesGoodsMap = " +
		 * JSONUtil.writeValueAsString(activitiesGoodsMap)); if
		 * (MapUtils.isNotEmpty(activitiesGoodsMap)) { logger.info("活动商品库存不足");
		 * resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
		 * resultMap.put(Constant.ERROR_CODE, Constant.GOODS_STOCK_LACK); return
		 * resultMap; }
		 * 
		 * resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		 * resultMap.put("ordersLists", ordersLists); return resultMap; } }
		 */

		// 判断普通商品库存
		List lackStockGoodsInfos = goodsNormsValueStockInterfaceDao.queryLackStockGoodsInfoInOrders(ordersIds);
		if (CollectionUtils.isNotEmpty(lackStockGoodsInfos)) {
			logger.info("lackStockGoodsInfos = " + JSONUtil.writeValueAsString(lackStockGoodsInfos));
			logger.info("普通商品库存不足");
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.GOODS_STOCK_LACK);
			return resultMap;
		}

		resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		resultMap.put("ordersLists", ordersLists);
		return resultMap;
	}

	/**
	 * 
	 * @MethodName paySuccess
	 * @Description 订单支付成功，修改订单状态、插入订单流程、修改商品购买人数
	 * 
	 * @author chenpy
	 * @date 2016年1月8日 下午5:35:36
	 * @param
	 * @return Map
	 * @throws Exception
	 * @throws DaoException
	 * @throws ServiceException
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map paySuccess(Map payMap) throws Exception {

		Map resultMap = new HashMap();

		TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = transactionManager.getTransaction(definition);

		try {
			String payModel = (String) payMap.get("payModel");
			String _customerId = (String) payMap.get("customerId");
			String orderIds = (String) payMap.get("orderIds");
			String leaveWords = (String) payMap.get("leaveWords");
			// String couponId = (String) payMap.get("couponId");
			// String areaCode = (String) payMap.get("areaCode");
			Integer[] ordersIdsArray = JSONUtil.readValueToBeanArray(orderIds, Integer.class);
			// List<OrdersList> ordersLists = (List<OrdersList>)
			// payMap.get("ordersLists");
			Integer customerId = Integer.parseInt(_customerId);
			File file = new File(this.getClass().getResource("").getFile() + "_batchCode_leavelWords.properties");
			/*
			 * Map<String, String> leaveWordsMap = new HashMap<>(); if
			 * (file.exists()) { Properties properties = PropertiesLoaderUtils
			 * .loadProperties(new EncodedResource(new FileSystemResource(file),
			 * "UTF-8")); for (int i = 0; i < ordersIdsArray.length; i++) {
			 * String leaveWordsKey = AESCoder.enCrypt("ORDERS_" +
			 * ordersIdsArray[i], "ORDERSCRYPT"); String ordersLeaveWords =
			 * properties.getProperty(leaveWordsKey); logger.info(
			 * "leaveWordsKey = " + leaveWordsKey + ", ordersLeaveWords= " +
			 * ordersLeaveWords); if (StringUtils.isNotEmpty(ordersLeaveWords))
			 * { leaveWordsMap.put(leaveWordsKey,
			 * URLDecoder.decode(URLDecoder.decode(ordersLeaveWords, "UTF-8"),
			 * "UTF-8")); } } }
			 */

			Integer[] orderIdArray = null;
			try {
				orderIdArray = JSONUtil.readValueToBeanArray(orderIds, Integer.class);
			} catch (Exception e) {
				throw new ServiceException(e);
			}

			List<OrdersList> ordersLists = ordersListInterfaceDao.queryOrdersByIds(Arrays.asList(orderIdArray));
			if (ordersLists.get(0).getStatus() < 2 && ordersLists.get(0).getStatus() > 0) {
				// 修改订单状态
				List<OrdersFlow> flows = new ArrayList<OrdersFlow>();
				List<Integer> ordersIds = new ArrayList<Integer>();
				Integer providerId = 0;
				Integer index = 0;
				for (Iterator iterator = ordersLists.iterator(); iterator.hasNext();) {
					OrdersList ordersList = (OrdersList) iterator.next();
					if (ordersList.getStatus() != 1) {
						iterator.remove();
						continue;
					}

					ordersList.setStatus(2);
					ordersList.setPayMode(payModel);
					// ordersList.setEndAreaCode(areaCode);
					// String leaveWordsKey = "123";
					if (StringUtils.isNotEmpty(leaveWords)) {
						ordersList.setLeaveWords(leaveWords);
					}
					OrdersFlow flow = new OrdersFlow();
					flow.setActionUser(customerId);
					flow.setOrdersId(ordersList.getId());
					flow.setStatus(2);
					flows.add(flow);
					ordersIds.add(ordersList.getId());

					// 扣减商品库存
					List<OrdersGoodsInfo> ordersGoodsInfos = ordersGoodsInfoInterfaceService
							.queryOrdersGoodsInfoByOrdersId(ordersList.getId());
					// 获取供应商ID用于推送
					providerId = goodsListInterfaceDao.queryGoodsListById(ordersGoodsInfos.get(0).getGoodsId())
							.getProviderId();
					for (OrdersGoodsInfo ordersGoodsInfo : ordersGoodsInfos) {
						GoodsNormsValueStock goodsNormsValueStock = new GoodsNormsValueStock();
						goodsNormsValueStock.setGoodsId(ordersGoodsInfo.getGoodsId());
						goodsNormsValueStock.setGoodsNormsValueId(ordersGoodsInfo.getNormsValueId());
						goodsNormsValueStock = goodsNormsValueStockInterfaceDao
								.queryGoodsNormsValueStockByGoodsId(goodsNormsValueStock);
						goodsNormsValueStockInterfaceService.updateAbatementGoodsNormsStockById(
								goodsNormsValueStock.getStockId(), ordersGoodsInfo.getBuyNum());// 扣减库存
					}

					// 扣减商品库存
					// 如果是活动或爆款商品订单，则还要扣减活动商品表活动商品数量
					/*
					 * if (ordersList.getIsActivity() == 1) { if
					 * (ordersList.getIdentifier() != null &&
					 * !ordersList.getIdentifier().equals("") &&
					 * (ordersList.getIdentifier().contains("PT_SPMQ"))) {
					 * synchronized (ordersList.getId()) { // 获取秒抢活动商品信息
					 * Map<String, Object> paramMap = new HashMap<String,
					 * Object>(); paramMap.put("ordersId", ordersList.getId());
					 * paramMap.put("identifier", ordersList.getIdentifier());
					 * Map<String, Object> activitiesGoodsMap = new
					 * HashMap<String, Object>(); activitiesGoodsMap =
					 * goodsNormsValueStockInterfaceDao.getSeckillStockNum(
					 * paramMap) ; if (MapUtils.isNotEmpty(activitiesGoodsMap))
					 * { logger.info("活动商品库存不足"); resultMap.put(Constant.STATUS,
					 * Constant.STATUS_ERROR);
					 * resultMap.put(Constant.ERROR_CODE,
					 * Constant.GOODS_STOCK_LACK); return resultMap; } else { //
					 * 扣减秒抢商品表活动商品数量
					 * goodsNormsValueStockInterfaceDao.updateSeckillNumById(
					 * ordersList.getId()); } } } if (ordersList.getIdentifier()
					 * != null && !ordersList.getIdentifier().equals("") &&
					 * (ordersList.getIdentifier().contains("PT_KJ"))) {
					 * synchronized (ordersList.getId()) { // 获取砍价活动商品信息
					 * Map<String, Object> paramMap = new HashMap<String,
					 * Object>(); paramMap.put("ordersId", ordersList.getId());
					 * paramMap.put("identifier", ordersList.getIdentifier());
					 * Map<String, Object> activitiesGoodsMap = new
					 * HashMap<String, Object>(); activitiesGoodsMap =
					 * goodsNormsValueStockInterfaceDao.getCutPriceStockNum(
					 * paramMap ); if (MapUtils.isNotEmpty(activitiesGoodsMap))
					 * { logger.info("活动商品库存不足"); resultMap.put(Constant.STATUS,
					 * Constant.STATUS_ERROR);
					 * resultMap.put(Constant.ERROR_CODE,
					 * Constant.GOODS_STOCK_LACK); return resultMap; } else { //
					 * 扣减砍价商品表活动商品数量
					 * goodsNormsValueStockInterfaceDao.updateCutPriceNumById(
					 * ordersList.getId()); } } } else if
					 * (ordersList.getIdentifier() != null &&
					 * !ordersList.getIdentifier().equals("") &&
					 * (ordersList.getIdentifier().contains("PT_TG_"))) {
					 * synchronized (ordersList.getId()) { // 获取团购活动商品信息
					 * Map<String, Object> paramMap = new HashMap<String,
					 * Object>(); paramMap.put("ordersId", ordersList.getId());
					 * paramMap.put("identifier", ordersList.getIdentifier());
					 * Map<String, Object> activitiesGoodsMap = new
					 * HashMap<String, Object>(); activitiesGoodsMap =
					 * goodsNormsValueStockInterfaceDao.getGroupBuyStockNum(
					 * paramMap ); if (MapUtils.isNotEmpty(activitiesGoodsMap))
					 * { logger.info("活动商品库存不足"); resultMap.put(Constant.STATUS,
					 * Constant.STATUS_ERROR);
					 * resultMap.put(Constant.ERROR_CODE,
					 * Constant.GOODS_STOCK_LACK); return resultMap; } else { //
					 * 扣减团购商品表活动商品数量
					 * goodsNormsValueStockInterfaceDao.updateGroupBuyNumById(
					 * ordersList.getId()); } } } else {
					 * goodsNormsValueStockInterfaceDao.updateActivityNumById(
					 * ordersList.getId());// 扣减活动商品表活动商品数量 } }
					 */

					index += 1;
				}

				if (CollectionUtils.isNotEmpty(ordersLists)) {

					ordersListInterfaceDao.batchUpdateOrdersList(ordersLists);
					ordersFlowInterfaceService.batchInsertOrdersFlow(flows);

					// 修改商品购买人数
					List<GoodsList> goodsLists = this.goodsListInterfaceImplService
							.selectGoodsInfoByOrdersIds(ordersIds);
					for (GoodsList goodsList : goodsLists) {
						goodsList.setSellNum(goodsList.getSellNum() + 1);
					}

					goodsListInterfaceImplService.batchUpdateGoodsList(goodsLists);

					Double payMoney = null;
					// 钱包支付（现金余额支付）
					if (payModel.equals("sayimoPayCash")) {
						String _payMoney = (String) payMap.get("payMoney");
						Double amounts = (Double) payMap.get("amounts");
						// 判断钱包余额
						Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(customerId);
						Double remainingCash = wallet.getRemainingCash().doubleValue();
						payMoney = Double.valueOf(_payMoney);
						payMoney = payMoney - amounts;
						if (payMoney <= 0) {
							payMoney = 0.00;
						}

						if (Double.compare(remainingCash, payMoney) < 0) { // 余额不足
							resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
							resultMap.put(Constant.ERROR_CODE, Constant.AVAILABLE_MONEY_NOT_ENOUGH);
							transactionManager.rollback(status);
							return resultMap;
						}
						remainingCash = remainingCash - payMoney;
						// 修改钱包余额和可用余额
						wallet.setRemainingCash(new BigDecimal(remainingCash));
						int num = walletInterfaceImplService.updateWallet(wallet);
						if (num < 1) {
							logger.error("update wallet error...");
							resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
							resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
							transactionManager.rollback(status);
							return resultMap;
						}
					}
					// 钱包支付（银积分支付）
					if (payModel.equals("sayimoPay")) {
						String _payMoney = (String) payMap.get("payMoney");
						Double amounts = (Double) payMap.get("amounts");
						// 判断钱包余额
						Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(customerId);
						Double remainingSilverScore = wallet.getRemainingSilverScore().doubleValue();
						payMoney = Double.valueOf(_payMoney);
						payMoney = payMoney - amounts;
						if (payMoney <= 0) {
							payMoney = 0.00;
						}

						if (Double.compare(remainingSilverScore, payMoney) < 0) { // 余额不足
							resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
							resultMap.put(Constant.ERROR_CODE, Constant.AVAILABLE_MONEY_NOT_ENOUGH);
							transactionManager.rollback(status);
							return resultMap;
						}
						remainingSilverScore = remainingSilverScore - payMoney;
						// 修改钱包余额和可用余额
						wallet.setRemainingSilverScore(new BigDecimal(remainingSilverScore));
						int num = walletInterfaceImplService.updateWallet(wallet);
						if (num < 1) {
							logger.error("update wallet error...");
							resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
							resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
							transactionManager.rollback(status);
							return resultMap;
						}
					}

					// 收入支出
					for (OrdersList ordersList : ordersLists) {
						/*
						 * Double kogistcsCostTotal = 0D;
						 * List<OrdersGoodsNormsInfo> goodsNormsInfos =
						 * ordersGoodsNormsInfoInterfaceService
						 * .queryOrdersGoodsNormsInfoByOrdersId(Constant.
						 * ORDERS_QUERY_DETAILS, orderId,
						 * Integer.parseInt(customerId)); if
						 * (CollectionUtils.isNotEmpty(goodsNormsInfos)) { for
						 * (OrdersGoodsNormsInfo ordersGoodsNormsInfo :
						 * goodsNormsInfos) { kogistcsCostTotal +=
						 * ordersGoodsNormsInfo.getLogistcsCost().doubleValue();
						 * } }
						 */
						Integer model = 0;
						Integer rewardType = 0;
						if (payModel.equals("sayimoPay")) {
							model = 3;
							rewardType = 1;
						} else if (payModel.equals("sayimoPayCash")) {
							model = 2;
							rewardType = 2;
						} else if (payModel.equals("weChatPay")) {
							model = 4;
							rewardType = 2;
						} else {
							model = 5;
							rewardType = 2;
						}
						WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
						expendRecord.setRewardType(rewardType);
						expendRecord.setExPend(ordersList.getSumMoney());
						expendRecord.setCustomerId(customerId);
						expendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
						expendRecord.setFromType(model);
						expendRecord.setOrderId(ordersList.getId());
						expendRecord.setOrderType(0);
						expendRecord.setCommet("来源订单号" + ordersList.getOrdersNo() + "的消费");
						walletIncomeExpendRecordServiceImpl.insertSelective(expendRecord);

					}
				}

				transactionManager.commit(status);
				Map dataMap = new HashMap();
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				dataMap.put(Constant.MSG, "支付成功");
				resultMap.put(Constant.DATA, dataMap);

				List<Integer> providerIds = new ArrayList<>();
				Integer goodsId = ordersGoodsInfoInterfaceService
						.queryOrdersGoodsInfoByOrdersId(ordersLists.get(0).getId()).get(0).getGoodsId();
				providerId = goodsListInterfaceDao.queryGoodsListById(goodsId).getProviderId();
				providerIds.add(providerId);
				// 获取供应商对应用户Id
				List<EnterpriseInfo> list = enterpriseInfoDao.getEnterpriseInfoByIds(providerIds);
				Customer customer = customerInterfaceImplDao.queryMemberCustomerById(list.get(0).getCustomerId());
				// 获取用户的设备号进行推送
				if (customer.getDeviceToken() != null && !customer.getDeviceToken().equals("")) {
					Integer deviceType = customer.getDeviceType();
					if (deviceType == 2) {
						// IOS推送
						String uMengAppKey = PropertiesUtils.getValue("UMENG_APP_KEY_IOS");
						String uMengAppSecret = PropertiesUtils.getValue("UMENG_APP_SECRET_IOS");
						;
						Demo demo = new Demo(uMengAppKey, uMengAppSecret);
						demo.sendIOSUnicast(customer.getDeviceToken());
					} else {
						// Android推送
						String uMengAppKey = PropertiesUtils.getValue("UMENG_APP_KEY_ANDROID");
						String uMengAppSecret = PropertiesUtils.getValue("UMENG_APP_SECRET_ANDROID");
						;
						Demo demo = new Demo(uMengAppKey, uMengAppSecret);
						demo.sendAndroidUnicast(customer.getDeviceToken());
					}
				}
				logger.info(customer.getDeviceToken());
			}
			return resultMap;
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e);
			transactionManager.rollback(status);
			throw new Exception(e);
		} catch (BaseAppException e) {
			e.printStackTrace();
			logger.error(e);
			throw new Exception(e);
		}
	}

	/**
	 * 
	 * @MethodName wxPayOrder
	 * @Description 微信预支付
	 * 
	 * @author chenpy
	 * @date 2016年1月9日 上午11:17:22
	 * @param
	 * @return Map
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map wxPayOrder(Map _paramMap, HttpServletRequest req)
			throws IllegalAccessException, InvocationTargetException, ServiceException {
		Map resultMap = new HashMap();

		try {
			logger.info("paramMap = " + JSONUtil.writeValueAsString(_paramMap));
			Map<String, String> requestMap = getRequestXml(_paramMap, req);
			String requestXML = requestMap.get("requestXML");
			logger.info("requestXML = " + requestXML);
			String result = getUnifiedorder(requestXML);
			logger.info("result = " + result);
			// 解析微信返回的信息，以Map形式存储便于取值
			Map<String, String> map = XMLUtil.doXMLParse(result);
			logger.info("XMLUTIL.DOXMLPARSE = " + JSONUtil.writeValueAsString(map));

			final SortedMap<Object, Object> params = new TreeMap<Object, Object>();
			if (map.get("result_code").equals("SUCCESS")) {
				params.put("appId", PropertiesUtils.getValue("APPID"));
				params.put("timeStamp", Long.toString(new Date().getTime()));
				params.put("nonceStr", WXUtil.getNonceStr());
				/*
				 * 获取预支付单号prepay_id后，需要将它参与签名。
				 * 微信支付最新接口中，要求package的值的固定格式为prepay_id=...
				 */
				params.put("package", "prepay_id=" + map.get("prepay_id"));

				/* 微信支付新版本签名算法使用MD5，不是SHA1 */
				params.put("signType", "MD5");
				/**
				 * 获取预支付prepay_id之后，需要再次进行签名，参与签名的参数有：appId、timeStamp、nonceStr、
				 * package、signType. 主意上面参数名称的大小写.
				 * 该签名用于前端js中WeixinJSBridge.invoke中的paySign的参数值
				 */
				String paySign = WXUtil.createSign("UTF-8", params);

				params.put("paySign", paySign);

				/*
				 * 预支付单号，前端ajax回调获取。由于js中package为关键字，所以，这里使用packageValue作为key。
				 */
				params.put("packageValue", "prepay_id=" + map.get("prepay_id"));

				/** 付款成功后，微信会同步请求我们自定义的成功通知页面，通知用户支付成功 */
				params.put("sendUrl", "");

				// 获取用户的微信客户端版本号，用于前端支付之前进行版本判断，微信版本低于5.0无法使用微信支付
				String userAgent = req.getHeader("user-agent");
				logger.info("userAgent = " + userAgent);
				if (userAgent.indexOf("MicroMessenger") == -1) {
					params.put("agent", 0);
				} else {
					char agent = userAgent.charAt(userAgent.indexOf("MicroMessenger") + 15);
					params.put("agent", new String(new char[] { agent }));
				}

			} else { // 订单支付失败
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PAY_ORDER_FAIL);

				return resultMap;
			}

			logger.info("params = " + JSONUtil.writeValueAsString(params));
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, params);
			logger.info("resultMap = " + JSONUtil.writeValueAsString(resultMap));

			// JMSMessage.sendMessage(requestMap.get("ordersNo"), 1);
			return resultMap;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 
	 * @MethodName getUnifiedorder
	 * @Description 从腾讯拉取预支付号
	 * @author chenpy
	 * @date 2016年1月9日 上午11:20:57
	 * @param
	 * @return String
	 * @throws Exception
	 * @VERSION 1.0.0
	 */
	private String getUnifiedorder(String requestXML) throws Exception {
		String result = null;
		HttpClient client = new HttpClient();
		PostMethod myPost = new PostMethod("https://api.mch.weixin.qq.com/pay/unifiedorder");
		client.getParams().setSoTimeout(300 * 1000);
		try {
			myPost.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
			int statusCode = client.executeMethod(myPost);
			if (statusCode == HttpStatus.SC_OK) {
				BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
				byte[] bytes = new byte[1024];
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				int count = 0;
				while ((count = bis.read(bytes)) != -1) {
					bos.write(bytes, 0, count);
				}
				byte[] strByte = bos.toByteArray();
				result = new String(strByte, 0, strByte.length, "utf-8");
				logger.info("result = " + result);
				bos.close();
				bis.close();
			}
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			myPost.releaseConnection();
			client.getHttpConnectionManager().closeIdleConnections(0);
		}

		return result;
	}

	/**
	 * 
	 * @MethodName getRequestXml
	 * @Description 生成获取微信支付批次号的请求参数
	 * 
	 * @author chenpy
	 * @date 2016年1月9日 上午11:28:08
	 * @param _paramMap(ordersNo,goodsName)
	 * @return String
	 * @throws DaoException
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map<String, String> getRequestXml(Map _paramMap, HttpServletRequest req)
			throws IllegalAccessException, InvocationTargetException, ServiceException, DaoException {
		Map<String, String> resultMap = new HashMap<>();
		String requestXML = null;
		String path = req.getContextPath();
		String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
		Double totalPrice = (Double) _paramMap.get("payPrice");
		/** 总金额(分为单位) */
		int total = (int) (totalPrice * 100);

		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		/** 公众号APPID */
		parameters.put("appid", PropertiesUtils.getValue("APPID"));
		/** 商户号 */
		parameters.put("mch_id", PropertiesUtils.getValue("MCHID")); // 1246536001
		/** 随机字符串 */
		parameters.put("nonce_str", WXUtil.getNonceStr());

		/** 订单批次号 */
		String orderIdJoin = (String) _paramMap.get("ordersNo");
		String orderId = (String) _paramMap.get("orderIds");
		parameters.put("out_trade_no", orderIdJoin);

		// 订单金额以分为单位，只能为整数
		parameters.put("total_fee", total);

		/* 支付方式为JSAPI支付 */
		parameters.put("trade_type", "JSAPI");
		/* 用户微信的openid，当trade_type为JSAPI的时候，该属性字段必须设置 */
		String customerId = (String) _paramMap.get("customerId");// ((String[])
																	// _paramMap.get("customerId"))[0];
		Customer customer = new Customer();
		customer.setId(Integer.parseInt(customerId));
		List<Customer> customers = customerInterfaceImplService.queryCustomerByCond(customer);
		logger.info(JSONUtil.writeValueAsString(customers.get(0).getOpenId()));
		String openId = customers.get(0).getOpenId();
		BeanUtils.copyProperties(customer, customers.get(0));
		parameters.put("openid", openId);
		/* 支付回调地址 */
		logger.info("notify_url = " + PropertiesUtils.getValue("SAYIMO_WXPAY_SUCCESS_NOTIFY_URL")
				+ "?customerIdOrderId=" + customer.getId() + "_" + JSONUtil.writeValueAsString(orderId));
		parameters.put("notify_url", PropertiesUtils.getValue("SAYIMO_WXPAY_SUCCESS_NOTIFY_URL") + "?customerIdOrderId="
				+ customer.getId() + "_" + JSONUtil.writeValueAsString(orderId));
		// 客户端本地ip
		parameters.put("spbill_create_ip", req.getRemoteAddr());
		// 商品名称
		String goodsName = (String) _paramMap.get("goodsName");
		parameters.put("body", goodsName);

		logger.info("parameters = " + JSONUtil.writeValueAsString(parameters));
		/** MD5进行签名，必须为UTF-8编码，注意上面几个参数名称的大小写 */
		String sign = WXUtil.createSign("UTF-8", parameters);

		// String sign = ret.get("signature");
		parameters.put("sign", sign);

		// 生成xml结构的数据，用于统一下单接口的请求
		requestXML = WXUtil.getRequestXml(parameters);
		logger.info("requestXML：" + requestXML);
		resultMap.put("requestXML", requestXML);
		resultMap.put("ordersNo", orderIdJoin);
		// 开始请求统一下单接口，获取预支付prepay_id
		return resultMap;
	}

	/**
	 * 
	 * @MethodName 微信支付成功回调
	 * @Description Description
	 * 
	 * @author chenpy
	 * @date 2016年1月9日 上午11:44:58
	 * @param
	 * @return Map
	 * @throws Exception
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public synchronized Map updatePaySuccess() throws Exception {
		Map resultMap = new HashMap();

		try {
			String customerId = request.getAttribute("customerId").toString();
			String orderIds = request.getParameter("orderIds");
			String applyType = request.getParameter("applyType");
			String couponId = request.getParameter("couponId");
			String payType = request.getParameter("payType");
			String out_trade_no = request.getParameter("out_trade_no");
			Integer[] orderIdArray = null;
			try {
				orderIdArray = JSONUtil.readValueToBeanArray(orderIds, Integer.class);
			} catch (Exception e) {
				throw new ServiceException(e);
			}

			logger.info("customerId = " + customerId + ", orderIds = " + orderIds + ", out_trade_no=" + out_trade_no);
			System.out.println(Arrays.asList(orderIdArray));
			List<OrdersList> ordersLists = ordersListInterfaceDao.queryOrdersByIds(Arrays.asList(orderIdArray));
			logger.info("ordersList = " + JSONUtil.writeValueAsString(ordersLists));

			// 验证订单是否支付成功
			// 支付宝支付
			if ("2".equals(payType) && applyType.equals("APP")) {
				boolean isPay = ALiPay.validAlipayTradeQuery(ordersLists.get(0).getOrdersNo());
				if (!isPay) {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR_CODE, Constant.PAY_ORDER_FAIL);
					return resultMap;
				}
			} else if ("1".equals(payType) && applyType.equals("APP")) { // 微信支付

				boolean isPay = WXPay.orderQuery(ordersLists.get(0).getOrdersNo());
				System.out.println("isPay=" + isPay);
				if (!isPay) {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR_CODE, Constant.PAY_ORDER_FAIL);
					return resultMap;
				}
			}

			Map payMap = new HashMap();
			payMap.put("ordersLists", ordersLists);
			payMap.put("customerId", customerId);
			if ("2".equals(payType)) {
				payMap.put("payModel", "aliPay");
			} else if ("1".equals(payType)) {
				payMap.put("payModel", "weChatPay");
			}

			payMap.put("orderIds", orderIds);
			payMap.put("couponId", couponId);
			logger.info("payMap = " + JSONUtil.writeValueAsString(payMap));
			paySuccess(payMap);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		} catch (Exception e) {
			throw new Exception(e);
		}

		return resultMap;
	}

	@Override
	public Double orderTotalMoney(Integer[] ordersIdArray) throws ServiceException {
		Map<String, Object> pm = queryOrdersTotalMoneyByIds(Arrays.asList(ordersIdArray));
		Double totalMoney = ((BigDecimal) pm.get("ordersTotalAmount")).doubleValue();
		return totalMoney;
	}

	private BigDecimal orderLogistcsCost(Integer[] ordersIdArray) throws ServiceException {
		try {
			return ordersListInterfaceDao.orderLogistcsCost(Arrays.asList(ordersIdArray));
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public Map<String, Object> queryOrdersTotalMoneyByIds(List<Integer> ids) throws ServiceException {
		try {
			return ordersListInterfaceDao.queryOrdersTotalMoneyByIds(ids);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
	}

	@Override
	public void updateOrdertotalAmountById(Integer id) throws ServiceException {
		try {
			ordersListInterfaceDao.updateOrdertotalAmountById(id);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
	}

	@Override
	public OrdersList queryOrdersListById(Integer id) throws ServiceException {
		try {
			return ordersListInterfaceDao.queryOrdersListById(id);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
	}

	/**
	 * @Title: propertyFill
	 * @Author: 王瑞清
	 * @Date:日期：2016年1月12日 时间：下午5:47:27
	 * @Description: 退换货参数值填充
	 * @param request
	 * @return GenerateOrdersReturnParams
	 * @Version 1.0.0
	 */
	private GenerateOrdersReturnParams propertyFill(HttpServletRequest request, File[] photoList)
			throws ServiceException {
		GenerateOrdersReturnParams generateOrdersReturnParams = new GenerateOrdersReturnParams();
		try {
			String orderId = request.getParameter("orderId");
			String customerId = request.getParameter("customerId");
			String type = request.getParameter("type");
			String applyExplain = request.getParameter("applyExplain");
			generateOrdersReturnParams.setOrderId(Integer.valueOf(orderId));
			generateOrdersReturnParams.setCustomerId(Integer.valueOf(customerId));
			generateOrdersReturnParams.setType(Integer.valueOf(type));
			generateOrdersReturnParams.setPhotoList(photoList);
			generateOrdersReturnParams.setApplyExplain(applyExplain);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
		return generateOrdersReturnParams;
	}

	/**
	 * @Package com.sayimo.maker.mall.orders.service.impl
	 * @Author 龚益君
	 * @MethodName:updateConfirmReceive
	 * @Description:确认收货
	 * @param paramMaps
	 * @return
	 * @throws ServiceException
	 * @Date 2017年3月9日,上午10:22:11
	 */
	@SuppressWarnings({ "rawtypes", "serial" })
	public Map<String, Object> updateConfirmReceive(Map<String, Object>... paramMaps) throws ServiceException {

		TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = transactionManager.getTransaction(definition);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		resultMap.put(Constant.DATA, new HashMap<String, String>() {
			{
				put(Constant.MSG, "收货成功");
			}
		});

		try {
			String orderId = null;
			String customerId = null;
			if (ArrayUtils.isNotEmpty(paramMaps)) {
				Map<String, Object> paramMap = paramMaps[0];
				orderId = paramMap.get("orderId").toString();
				customerId = paramMap.get("customerId").toString();
			} else if (request != null) {
				orderId = request.getParameter("orderId");
				customerId = request.getParameter("customerId");
			}

			if (StringUtils.isEmpty(orderId) || StringUtils.isEmpty(customerId)) {
				logger.error("params error..., orderId = " + orderId + ", customerId = " + customerId);
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			OrdersList order = ordersListInterfaceDao.queryOrdersListById(Integer.valueOf(orderId));
			if (order == null) { // 订单不存在
				logger.error("order is null");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			GenerateOrdersFlowParams generateOrdersFlowParams = new GenerateOrdersFlowParams(order.getId(),
					Integer.valueOf(customerId), 6);
			Map<String, Object> pm = new HashMap<>();
			pm.put("id", order.getId());
			pm.put("status", 6);
			ordersListInterfaceDao.updateOrdersListStatus(pm);
			ordersFlowInterfaceService.insertOrdersFlow(generateOrdersFlowParams);
			Customer customer = new Customer();
			customer.setId(Integer.parseInt(customerId));
			customer = customerInterfaceImplService.queryCustomerByCond(customer).get(0);
			String memberName = customer.getAlias();
			// 查订单下所有商品
			List goodsInfos = ordersGoodsInfoInterfaceService.queryOrdersGoodsInfoByOrderId(order.getId());
			List<Integer> providerIdList = new ArrayList<>();
			Double pushMoney = 0D;
			Double incomeScore = 0D;
			Double restockPriceAll = 0D;
			Double accumulaTurnover = 0D;
			Integer discount = 0;
			Integer isGiveScore = 0;
			BigDecimal pushMoneyOne = new BigDecimal(0);

			// 如果发货后没有确认收货，自动转账给供应商了，则确认收货时不再转账给供应商
			// 查询交易记录判断该订单是否已转账给供应商
			Map incomeExpendRecordMap = new HashMap();
			incomeExpendRecordMap.put("queryType", 1);
			incomeExpendRecordMap.put("orderType", "0");
			incomeExpendRecordMap.put("rewardType", 2);
			incomeExpendRecordMap.put("orderId", Integer.valueOf(orderId));

			EnterpriseWalletIncomeExpendRecord walletIncomeExpendRecord = enterpriseWalletIncomeExpendRecordInterfaceDao
					.getWalletIncomeExpend(incomeExpendRecordMap);
			String recordBatchCode = null;
			if (walletIncomeExpendRecord != null) {
				recordBatchCode = walletIncomeExpendRecord.getRecordBatchCode();
			} else {
				recordBatchCode = GeneratorUtils.generatorOrdersNo("003");
			}
			for (Object object : goodsInfos) {
				Map ordersGoodsInfoMap = (Map) object;
				Integer normsValueId = Integer.valueOf(ordersGoodsInfoMap.get("normsValueId").toString());
				Integer goodsId = (Integer) ordersGoodsInfoMap.get("goodsId");
				Integer buyNum = (Integer) ordersGoodsInfoMap.get("buyNum");
				Double transactionPrice = Double.parseDouble(ordersGoodsInfoMap.get("transactionPrice").toString());
				GoodsList goodsList = goodsListInterfaceImplService.queryGoodsListById(goodsId);
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("goodsId", goodsId);
				paramMap.put("goodsNormsValueId", normsValueId);

				Map<String, Object> map = goodsNormsValueStockInterfaceService.getNormsValueStockByMap(paramMap);

				// 获取对应每一个商品的discount，如果是金商城且送积分，倍率大于6 或者 银商城倍率大于6.
				isGiveScore = goodsList.getIsGiveScore();
				discount = Integer.valueOf(map.get("discount").toString());
				Double restockPrice = (Double) (Double.parseDouble(map.get("restockPrice").toString()) * buyNum);// 进货价
				Double turnover = (Double) (Double.parseDouble(map.get("preferentialPrice").toString()) * buyNum);
				restockPriceAll = restockPrice + restockPriceAll;
				accumulaTurnover = turnover + accumulaTurnover;
				providerIdList.add(goodsList.getProviderId());
				pushMoney = pushMoney + transactionPrice * buyNum;
				Map goodsBrokerageMap = goodsListInterfaceImplService.queryGoodsBrokerageById(goodsId);
				if (goodsBrokerageMap != null && !goodsBrokerageMap.isEmpty()) {
					Integer pointsType = Integer.valueOf(goodsBrokerageMap.get("pointsType").toString());// 佣金类型
					if (pointsType - 1 == 0) {
						// 佣金
						Double points = Double.valueOf(goodsBrokerageMap.get("points").toString());

						if (points != null && points != 0) {
							incomeScore += points * buyNum;
						}
					} else if (pointsType - 2 == 0) {
						// 佣金百分比（pointsPercent%）
						Double pointsPercent = Double.valueOf(goodsBrokerageMap.get("pointsPercent").toString()) / 100;

						if (pointsPercent != null && pointsPercent != 0) {
							incomeScore += transactionPrice * pointsPercent * buyNum;
						}
					}
				}
			}
			// 订单为金商城订单才有返还
			if (order.getMallType() - 1 == 0) {
				// 返还银积分
				if (incomeScore.compareTo(0D) != 0) {
					WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
					expendRecord.setRewardType(1);
					expendRecord.setCustomerId(customer.getId());
					expendRecord.setInCome(new BigDecimal(incomeScore));
					expendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
					expendRecord.setCommet("收到返还银积分");
					expendRecord.setOrderType(6);
					expendRecord.setFromType(7);
					expendRecord.setRecordBatchCode(recordBatchCode);
					walletIncomeExpendRecordServiceImpl.insertSelective(expendRecord);

					logger.info("customerId = " + customer.getId());
					Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(customer.getId());
					wallet.setRemainingSilverScore(
							new BigDecimal(wallet.getRemainingSilverScore().doubleValue() + incomeScore));
					wallet.setAccumulaSilverScore(
							new BigDecimal(wallet.getAccumulaSilverScore().doubleValue() + incomeScore));
					walletInterfaceImplService.updateWallet(wallet);
				}
			}
			// 循环供应商获取上级转账
			Map tProParamMap = new HashMap();
			String payPrice = null;
			List<EnterpriseInfo> enterpriseInfoList = enterpriseInfoDao.getEnterpriseInfoByIds(providerIdList);
			Customer proCustomer = new Customer();
			Integer proCustomerId = enterpriseInfoList.get(0).getCustomerId();
			if (proCustomerId != null && proCustomerId != 0) {
				proCustomer.setId(enterpriseInfoList.get(0).getCustomerId());
				proCustomer = customerInterfaceImplService.queryCustomerByCond(proCustomer).get(0);

				if (proCustomer.getParentId() != null && proCustomer.getParentId() != 0) {
					Customer parent = new Customer();
					parent.setId(proCustomer.getParentId());
					parent = customerInterfaceImplService.queryCustomerByCond(parent).get(0);
					Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(proCustomer.getParentId());
					if (parent.getMakerLevel() > 0 && proCustomer.getAwardRule() - 2 == 0) {
						Double sysValue = 0D;
						if (parent.getMakerLevel() - 1 == 0) {
							sysValue = Double
									.parseDouble(baseConfigDao.getConfigByKey("GOLD_PROVIDER_COMMISSION_SALES")) / 100D;
						} else {
							sysValue = Double.parseDouble(
									baseConfigDao.getConfigByKey("SILVER_PROVIDER_COMMISSION_SALES")) / 100D;
						}
						BigDecimal remainingCash = new BigDecimal(
								pushMoney * sysValue + wallet.getRemainingCash().doubleValue());
						BigDecimal accumulaCash = new BigDecimal(
								pushMoney * sysValue + wallet.getAccumulaCash().doubleValue());
						wallet.setRemainingCash(remainingCash);
						wallet.setAccumulaCash(accumulaCash);
						Integer count = walletInterfaceImplService.updateWallet(wallet);
						
						if (count > 0) {
							// 收入支出记录
							WalletIncomeExpendRecord incomeExpendRecord = new WalletIncomeExpendRecord();
							incomeExpendRecord.setRewardType(2); // 现金奖励
							incomeExpendRecord.setCustomerId(parent.getId());
							incomeExpendRecord
									.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
							incomeExpendRecord.setInCome(new BigDecimal(pushMoney * sysValue));
							incomeExpendRecord.setCommet("供应商上级获取销售额提成");
							incomeExpendRecord.setOrderType(6);
							incomeExpendRecord.setFromType(7);
							walletIncomeExpendRecordServiceImpl.insertSelective(incomeExpendRecord);
						}
					}
				}
			}

			if (walletIncomeExpendRecord == null) {
				EnterpriseWallet proWallet = enterpriseWalletInterfaceDao
						.queryWalletByCustomerId(proCustomer.getProviderRefId());
				Integer bindType = proWallet.getBindType();
				if (bindType - 1 == 0) {
					// 转货款给供应商(放入转账参数)

					String payeeProAccount = proWallet.getBankCodeNo();
					String payeeProRealName = proWallet.getBankBindUserName();
//					restockPriceAll = (Double) (restockPriceAll - restockPriceAll * 0.006);//扣除手续费（暂时不扣）
					DecimalFormat doubleFormat = new DecimalFormat("######0.00");
					payPrice = doubleFormat.format(restockPriceAll);
					tProParamMap.put("payee_account", payeeProAccount);
					tProParamMap.put("payee_real_name", payeeProRealName);
					tProParamMap.put("payPrice", payPrice);
					tProParamMap.put("remark", "供应商货款");

					// 转货款给供应商
					Map tProResultMap = ALiTransfer.aliTransfer(tProParamMap); // 转账结果
					if (tProResultMap.get(Constant.STATUS).equals(Constant.STATUS_ERROR)) { // 失败
						transactionManager.rollback(status);
						resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
						resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
						return resultMap;
					}
					String outProBizNo = String.valueOf(JSONUtil
							.readValueToMap(JSONUtil.writeValueAsString(tProResultMap.get("data"))).get("out_biz_no")); // 转账交易订单号//
																														// //
																														// 转账交易订单号
					tProResultMap = ALiTransfer.validAliTransfer(outProBizNo);
					if (tProResultMap.get(Constant.STATUS).equals(Constant.STATUS_SUCCESS)) { // 交易
						// 收入支出记录
						EnterpriseWalletIncomeExpendRecord incomeExpendRecord = new EnterpriseWalletIncomeExpendRecord();
						incomeExpendRecord.setRewardType(2); // 现金
						incomeExpendRecord.setInCome(new BigDecimal(payPrice));
						incomeExpendRecord.setProviderRefId(proCustomer.getProviderRefId());
						incomeExpendRecord.setCommet("供应商货款");
						incomeExpendRecord.setEmsNo(outProBizNo);
						incomeExpendRecord.setOrderType(0);
						incomeExpendRecord.setFromType(5);
						incomeExpendRecord.setOrderId(Integer.valueOf(orderId));
						incomeExpendRecord.setRecordBatchCode(recordBatchCode);
						incomeExpendRecord.setTransferStatus(3);
						incomeExpendRecord.setTurnover(new BigDecimal(accumulaTurnover));
						enterpriseWalletIncomeExpendRecordInterfaceDao.insertSelective(incomeExpendRecord);
					}
				} else {
					proWallet.setAccumulaCash(proWallet.getAccumulaCash().add(new BigDecimal(restockPriceAll)));
					proWallet.setRemainingCash(proWallet.getRemainingCash().add(new BigDecimal(restockPriceAll)));
					proWallet
							.setAccumulaTurnover(proWallet.getAccumulaTurnover().add(new BigDecimal(accumulaTurnover)));
					Integer count = enterpriseWalletInterfaceDao.updateWallet(proWallet);
					String emsNo = GeneratorUtils.generatorOrdersNo("003");
					if (count > 0) { // 交易
						// 收入支出记录
						EnterpriseWalletIncomeExpendRecord incomeExpendRecord = new EnterpriseWalletIncomeExpendRecord();
						incomeExpendRecord.setRewardType(2); // 现金
						incomeExpendRecord.setInCome(new BigDecimal(payPrice));
						incomeExpendRecord.setProviderRefId(proCustomer.getProviderRefId());
						incomeExpendRecord.setCommet("供应商货款");
						incomeExpendRecord.setEmsNo(emsNo);
						incomeExpendRecord.setOrderType(0);
						incomeExpendRecord.setFromType(1);
						incomeExpendRecord.setOrderId(Integer.valueOf(orderId));
						incomeExpendRecord.setRecordBatchCode(recordBatchCode);
						incomeExpendRecord.setTransferStatus(1);
						incomeExpendRecord.setTurnover(new BigDecimal(accumulaTurnover));
						enterpriseWalletIncomeExpendRecordInterfaceDao.insertSelective(incomeExpendRecord);
					}
				}
			}

			transactionManager.commit(status);
			return resultMap;

		} catch (Exception e) {
			logger.error(e);
			transactionManager.rollback(status);
			throw new ServiceException(e);
		}
	}

	/**
	 * @Package com.sayimo.maker.mall.orders.service.impl
	 * @Author 谭新
	 * @MethodName: unconfirmOrderTransferProvider
	 * @Description:转账给供应商
	 * @Date 2017年4月12日,下午3:36:54
	 */
	@Override
	public Map<String, Object> unconfirmOrderTransferProvider(Map<String, Object> paramMaps) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		resultMap.put(Constant.DATA, new HashMap<String, String>() {
			{
				put(Constant.MSG, "转账成功");
			}
		});
		try {
			Map tProParamMap = new HashMap();
			String payPrice = null;

			Integer orderId = Integer.valueOf(paramMaps.get("orderId").toString());

			// 如果发货后没有确认收货，自动转账给供应商了，则确认收货时不再转账给供应商
			// 查询交易记录判断该订单是否已转账给供应商
			Map incomeExpendRecordMap = new HashMap();
			incomeExpendRecordMap.put("queryType", 1);
			incomeExpendRecordMap.put("orderType", "0");
			incomeExpendRecordMap.put("rewardType", 2);
			incomeExpendRecordMap.put("orderId", Integer.valueOf(orderId));

			EnterpriseWalletIncomeExpendRecord walletIncomeExpendRecord = enterpriseWalletIncomeExpendRecordInterfaceDao
					.getWalletIncomeExpend(incomeExpendRecordMap);

			if (walletIncomeExpendRecord == null) {

				// 查订单下所有商品
				List goodsInfos = ordersGoodsInfoInterfaceService.queryOrdersGoodsInfoByOrderId(orderId);
				List<Integer> providerIdList = new ArrayList<>();
				Double incomeScore = 0D;
				Double restockPriceAll = 0D;
				Double accumulaTurnover = 0D;
				for (Object object : goodsInfos) {
					Map ordersGoodsInfoMap = (Map) object;
					Integer normsValueId = Integer.valueOf(ordersGoodsInfoMap.get("normsValueId").toString());
					Integer goodsId = (Integer) ordersGoodsInfoMap.get("goodsId");
					Integer buyNum = (Integer) ordersGoodsInfoMap.get("buyNum");
					Double transactionPrice = Double.parseDouble(ordersGoodsInfoMap.get("transactionPrice").toString());
					GoodsList goodsList = goodsListInterfaceImplService.queryGoodsListById(goodsId);
					Map<String, Object> paramMap = new HashMap<>();
					paramMap.put("goodsId", goodsId);
					paramMap.put("goodsNormsValueId", normsValueId);
					Map<String, Object> map = goodsNormsValueStockInterfaceService.getNormsValueStockByMap(paramMap);
					Double restockPrice = (Double) (Double.parseDouble(map.get("restockPrice").toString()) * buyNum);// 进货价
					Double turnover = (Double) (Double.parseDouble(map.get("preferentialPrice").toString()) * buyNum);
					restockPriceAll = restockPrice + restockPriceAll;
					accumulaTurnover = turnover + accumulaTurnover;
					providerIdList.add(goodsList.getProviderId());
				}

				List<EnterpriseInfo> enterpriseInfoList = enterpriseInfoDao.getEnterpriseInfoByIds(providerIdList);
				Customer proCustomer = new Customer();
				Integer proCustomerId = enterpriseInfoList.get(0).getCustomerId();
				if (proCustomerId != null && proCustomerId != 0) {
					proCustomer.setId(enterpriseInfoList.get(0).getCustomerId());
					proCustomer = customerInterfaceImplService.queryCustomerByCond(proCustomer).get(0);
				}

				EnterpriseWallet proWallet = enterpriseWalletInterfaceDao
						.queryWalletByCustomerId(proCustomer.getProviderRefId());
				Integer bindType = proWallet.getBindType();
				String recordBatchCode = GeneratorUtils.generatorOrdersNo("003");
				if (bindType - 1 == 0) {
					String payeeProAccount = proWallet.getBankCodeNo();
					String payeeProRealName = proWallet.getBankBindUserName();
//					restockPriceAll = (Double) (restockPriceAll - restockPriceAll * 0.006);//扣除手续费（暂时不扣）
					DecimalFormat doubleFormat = new DecimalFormat("######0.00");
					payPrice = doubleFormat.format(restockPriceAll);
					tProParamMap.put("payee_account", payeeProAccount);
					tProParamMap.put("payee_real_name", payeeProRealName);
					tProParamMap.put("payPrice", payPrice);
					tProParamMap.put("remark", "供应商货款");

					// 转货款给供应商

					Map tProResultMap = ALiTransfer.aliTransfer(tProParamMap); // 转账结果
					if (tProResultMap.get(Constant.STATUS).equals(Constant.STATUS_ERROR)) { // 失败
						resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
						resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
						return resultMap;
					}
					String outProBizNo = String.valueOf(JSONUtil
							.readValueToMap(JSONUtil.writeValueAsString(tProResultMap.get("data"))).get("out_biz_no")); // 转账交易订单号//
					tProResultMap = ALiTransfer.validAliTransfer(outProBizNo);
					if (tProResultMap.get(Constant.STATUS).equals(Constant.STATUS_SUCCESS)) { // 交易
						// 收入支出记录
						EnterpriseWalletIncomeExpendRecord incomeExpendRecord = new EnterpriseWalletIncomeExpendRecord();
						incomeExpendRecord.setRewardType(2); // 现金
						incomeExpendRecord.setInCome(new BigDecimal(payPrice));
						incomeExpendRecord.setProviderRefId(proCustomer.getProviderRefId());
						incomeExpendRecord.setCommet("供应商货款");
						incomeExpendRecord.setEmsNo(outProBizNo);
						incomeExpendRecord.setOrderType(0);
						incomeExpendRecord.setFromType(5);
						incomeExpendRecord.setOrderId(Integer.valueOf(orderId));
						incomeExpendRecord.setRecordBatchCode(recordBatchCode);
						incomeExpendRecord.setTransferStatus(3);
						incomeExpendRecord.setTurnover(new BigDecimal(accumulaTurnover));
						enterpriseWalletIncomeExpendRecordInterfaceDao.insertSelective(incomeExpendRecord);
					}
				} else {
					proWallet.setAccumulaCash(proWallet.getAccumulaCash().add(new BigDecimal(restockPriceAll)));
					proWallet.setRemainingCash(proWallet.getRemainingCash().add(new BigDecimal(restockPriceAll)));
					proWallet
							.setAccumulaTurnover(proWallet.getAccumulaTurnover().add(new BigDecimal(accumulaTurnover)));
					Integer count = enterpriseWalletInterfaceDao.updateWallet(proWallet);
					String emsNo = GeneratorUtils.generatorOrdersNo("003");
					if (count > 0) { // 交易
						// 收入支出记录
						EnterpriseWalletIncomeExpendRecord incomeExpendRecord = new EnterpriseWalletIncomeExpendRecord();
						incomeExpendRecord.setRewardType(2); // 现金
						incomeExpendRecord.setInCome(new BigDecimal(payPrice));
						incomeExpendRecord.setProviderRefId(proCustomer.getProviderRefId());
						incomeExpendRecord.setCommet("供应商货款");
						incomeExpendRecord.setEmsNo(emsNo);
						incomeExpendRecord.setOrderType(0);
						incomeExpendRecord.setFromType(1);
						incomeExpendRecord.setOrderId(Integer.valueOf(orderId));
						incomeExpendRecord.setRecordBatchCode(recordBatchCode);
						incomeExpendRecord.setTransferStatus(1);
						incomeExpendRecord.setTurnover(new BigDecimal(accumulaTurnover));
						enterpriseWalletIncomeExpendRecordInterfaceDao.insertSelective(incomeExpendRecord);
					}
				}
			}
			return resultMap;
		} catch (Exception de) {
			de.printStackTrace();
			throw new ServiceException(de);
		}
	}

	@Override
	public Integer updateOrdersListStatus(Integer status, Integer id) throws ServiceException {
		try {
			Map<String, Object> pm = new HashMap<String, Object>();
			pm.put("id", id);
			pm.put("status", status);
			return ordersListInterfaceDao.updateOrdersListStatus(pm);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
	}

	/**
	 * @Title: addOrderReceiveAddress
	 * @Author: chenpy
	 * @Date:日期：2016年1月13日 时间：下午4:53
	 * @Description: 添加(修改)订单收货地址
	 * @return
	 * @Version 1.0.0
	 */
	@SuppressWarnings({ "unchecked", "rawtypes", "serial" })
	public Map<String, Object> addOrderReceiveAddress(HttpServletRequest request) throws ServiceException {
		Map resultMap = new HashMap();
		String orderIds = request.getParameter("orderIds");
		String customerId = request.getAttribute("customerId").toString();
		try {

			logger.info("orderIds = " + orderIds + ", customerId = " + customerId);
			if (StringUtils.isEmpty(orderIds) || StringUtils.isEmpty(customerId)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}

			ReceivingAddress address = new ReceivingAddress();
			address.setCustomerId(Integer.parseInt(customerId));
			address = receivingAddressInterfaceService.selectDefaultAddress(address);
			if (address == null) {
				logger.error("recevingAddress is null");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}

			List<Integer> ids = JSONUtil.readValueToBeanList(orderIds, Integer.class);
			List<OrdersReceivingAddress> ordersReceivingAddresses = ordersReceivingAddressInterfaceService
					.queryOrderReceivingCountByOrdersIds(ids);
			if (CollectionUtils.isEmpty(ordersReceivingAddresses)) {
				logger.error("ordersReceivingAddresses is null");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}

			for (OrdersReceivingAddress ordersReceivingAddress : ordersReceivingAddresses) {
				ordersReceivingAddress.setAddress(address.getAddress());
				ordersReceivingAddress.setReceivingPeople(address.getReceivingPeople());
				ordersReceivingAddress.setTelePhone(address.getTelephone());
				ordersReceivingAddress.setAreaCode(address.getAreaCode());
			}

			ordersReceivingAddressInterfaceService.batchUpdateOrderRecevingAddr(ordersReceivingAddresses);

			// 修改订单下商品运费信息
			List<OrdersList> ordersLists = ordersListInterfaceDao.queryOrdersByIds(ids);
			if (CollectionUtils.isNotEmpty(ordersLists)) {
				for (OrdersList ordersList : ordersLists) {
					List goodsInfo = ordersGoodsInfoInterfaceService.queryOrdersGoodsInfoByOrderId(ordersList.getId());
					setOrdersSumAmount(goodsInfo, ordersList, address.getAreaCode());
				}
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, new HashMap<String, String>() {
				{
					put(Constant.MSG, "新增成功");
				}
			});
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}

		return resultMap;
	}

	/**
	 * @package com.sayimo.school.mall.module.order.service.impl
	 * @author chenpy
	 * @Title:
	 * @Description: 计算订单运费信息
	 * @param
	 * @throws @return
	 *             boolean
	 * @date 2016年7月27日
	 */
	private boolean setOrdersSumAmount(List goodsInfo, OrdersList ordersList, String areaCode) throws ServiceException {

		try {
			Integer[] goodsIds = new Integer[0], normsValueIds = new Integer[0], goodsInfoIds = new Integer[0];

			for (Object object : goodsInfo) {
				Map ordersGoodsInfoMap = (Map) object;
				Integer id = Integer.parseInt(ordersGoodsInfoMap.get("id").toString());
				Integer goodsId = Integer.parseInt(ordersGoodsInfoMap.get("goodsId").toString());
				Integer normsValueId = (Integer) ordersGoodsInfoMap.get("normsValueId");
				goodsIds = (Integer[]) ArrayUtils.add(goodsIds, goodsId);
				normsValueIds = (Integer[]) ArrayUtils.add(normsValueIds, normsValueId);
				goodsInfoIds = (Integer[]) ArrayUtils.add(goodsInfoIds, id);
			}

			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("ordersId", ordersList.getId());
			paramMap.put("goodsIds", goodsIds);
			paramMap.put("normsValueIds", normsValueIds);
			BigDecimal totalAmount = ordersGoodsInfoInterfaceService.getOrdersTotalAmount(paramMap);

			// 活动商品
			if (ordersList.getIsActivity() != null && ordersList.getIsActivity() == 1
					&& StringUtils.isNotEmpty(ordersList.getIdentifier())) {
				logger.info("ordersList is activity");
				List<OrdersGoodsInfo> goodsInfos = new ArrayList<>();
				Map ordersGoodsInfoMap = (Map) goodsInfo.get(0);
				OrdersGoodsInfo ordersGoodsInfo = new OrdersGoodsInfo();
				ordersGoodsInfo.setId(Integer.parseInt(ordersGoodsInfoMap.get("id").toString()));
				BigDecimal totalLogistcsCost = new BigDecimal(12);

				if (ordersList.getIdentifier().contains("CYGHMZS") || ordersList.getIdentifier().contains("CYBK")) {
					if (Integer.parseInt(areaCode) < 0 || gzcode.equals(areaCode.substring(0, 2))) {
						totalLogistcsCost = new BigDecimal(8);
					}
				} else if (ordersList.getIdentifier().contains("ZXXSZS")) {
					totalLogistcsCost = new BigDecimal(0);
				}

				ordersGoodsInfo.setLogistcsCost(totalLogistcsCost);
				goodsInfos.add(ordersGoodsInfo);

				ordersList.setTotalAmount(totalAmount);
				ordersList.setSumMoney(totalAmount.add(totalLogistcsCost));
				ordersListInterfaceDao.updateOrdersList(ordersList);
				ordersGoodsInfoInterfaceDao.batchUpdateOrdersGoodsInfos(goodsInfos);
				return true;
			}
			if (CollectionUtils.isEmpty(goodsInfo)) {
				logger.info("goodsInfo is null or goodsInfo.length is 0");
				return true;
			}

			List<OrdersGoodsInfo> goodsInfos = new ArrayList<>();
			for (int i = 0; i < goodsInfoIds.length; i++) {
				OrdersGoodsInfo ordersGoodsInfo = new OrdersGoodsInfo();
				ordersGoodsInfo.setId(goodsInfoIds[i]);
				ordersGoodsInfo.setLogistcsCost(new BigDecimal(0));
				goodsInfos.add(ordersGoodsInfo);
			}
			logger.info("goodsInfos = " + JSONUtil.writeValueAsString(goodsInfos));

			BigDecimal freeMinConsumption = getFreeMinConsumption();
			// 免运费(订单金额大于免运费最低消费额，或者是校内地址)
			if ((freeMinConsumption == null || freeMinConsumption.compareTo(totalAmount) < 0)
					|| (Integer.parseInt(areaCode) < 0)) {
				ordersGoodsInfoInterfaceDao.batchUpdateOrdersGoodsInfos(goodsInfos);

				// 同时修改订单金额
				ordersList.setTotalAmount(totalAmount);
				ordersList.setSumMoney(totalAmount);
				ordersListInterfaceDao.updateOrdersList(ordersList);
				return true;
			}

			// 按件计算运费
			paramMap = new HashMap<>();
			String goodsIdJoins = StringUtils.join(goodsIds, ",");
			// 订单总金额(不包含运费)
			paramMap.put("areaCode", areaCode);
			paramMap.put("goodsIdJoins", goodsIdJoins);
			paramMap.put("priceType", 1);
			paramMap.put("ordersId", ordersList.getId());
			Map logisticsGoodsIdMap = ordersGoodsInfoInterfaceDao.getLogisticsGoodsId(paramMap);
			logger.info("logisticsGoodsIdMap = " + JSONUtil.writeValueAsString(logisticsGoodsIdMap));
			BigDecimal totalLogistcsCost = new BigDecimal(0);
			if (MapUtils.isNotEmpty(logisticsGoodsIdMap) && logisticsGoodsIdMap.containsKey("id")
					&& logisticsGoodsIdMap.get("id") != null) {
				Integer maxGoodsId = Integer.parseInt(logisticsGoodsIdMap.get("id").toString());
				Integer logisticsCostId = Integer.parseInt(logisticsGoodsIdMap.get("logisticsCostId").toString());
				Integer buyNum = Integer.parseInt(logisticsGoodsIdMap.get("buyNum").toString());
				Integer goodsInfoId = Integer.parseInt(logisticsGoodsIdMap.get("goodsInfoId").toString());
				BigDecimal logistcsCostNum = ordersGoodsInfoInterfaceDao.getLogisticsCostByAreaCode(areaCode,
						maxGoodsId, logisticsCostId, buyNum);

				logger.info("goodsInfoId = " + goodsInfoId);
				// 计算运费
				for (OrdersGoodsInfo info : goodsInfos) {
					logger.info("info.getId = " + info.getId() + ", goodsInfoId = " + goodsInfoId);
					if (info.getId().toString().equals(goodsInfoId.toString())) {
						logger.info("info.logistics = " + logistcsCostNum);
						info.setLogistcsCost(logistcsCostNum);
					}
				}

				totalLogistcsCost = totalLogistcsCost.add(logistcsCostNum);
				logger.info("totalLogistcsCost = " + totalLogistcsCost);
			}
			logger.info("goodsInfos = " + JSONUtil.writeValueAsString(goodsInfos));
			// 按重计算运费
			paramMap.put("priceType", 2);
			logisticsGoodsIdMap = ordersGoodsInfoInterfaceDao.getLogisticsGoodsId(paramMap);
			logger.info("logisticsGoodsIdMap = " + JSONUtil.writeValueAsString(logisticsGoodsIdMap));
			if (MapUtils.isNotEmpty(logisticsGoodsIdMap) && logisticsGoodsIdMap.containsKey("id")
					&& logisticsGoodsIdMap.get("id") != null) {
				Integer maxGoodsId = Integer.parseInt(logisticsGoodsIdMap.get("id").toString());
				Integer logisticsCostId = Integer.parseInt(logisticsGoodsIdMap.get("logisticsCostId").toString());
				Integer buyNum = Integer.parseInt(logisticsGoodsIdMap.get("buyNum").toString());
				Integer goodsInfoId = Integer.parseInt(logisticsGoodsIdMap.get("goodsInfoId").toString());

				// 计算运费
				BigDecimal logistcsCostWeight = ordersGoodsInfoInterfaceDao.getLogisticsCostByAreaCode(areaCode,
						maxGoodsId, logisticsCostId, buyNum);

				logger.info("goodsInfoId = " + goodsInfoId);
				// 计算运费
				for (OrdersGoodsInfo info : goodsInfos) {
					logger.info("info.getId = " + info.getId() + ", goodsInfoId = " + goodsInfoId);
					if (info.getId().toString().equals(goodsInfoId.toString())) {
						logger.info("info.logistics = " + logistcsCostWeight);
						info.setLogistcsCost(logistcsCostWeight);
					}
				}

				totalLogistcsCost = totalLogistcsCost.add(logistcsCostWeight);
				logger.info("totalLogistcsCost = " + totalLogistcsCost);
			}

			if (CollectionUtils.isNotEmpty(goodsInfos)) {
				ordersGoodsInfoInterfaceDao.batchUpdateOrdersGoodsInfos(goodsInfos);
			}

			// 修改订单金额
			ordersList.setTotalAmount(totalAmount);
			ordersList.setSumMoney(totalAmount.add(totalLogistcsCost));
			ordersListInterfaceDao.updateOrdersList(ordersList);
			return true;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * @Title: cancelOrder
	 * @Author: chenpy
	 * @Date:日期：2016年1月13日 时间：下午4:53
	 * @Description: 取消订单
	 * @return
	 * @Version 1.0.0
	 */
	@SuppressWarnings({ "unchecked", "rawtypes", "serial" })
	public Map<String, Object> deleteOrder(HttpServletRequest request) throws ServiceException {
		Map resultMap = new HashMap();
		try {
			String orderId = request.getParameter("orderId");
			if (StringUtils.isEmpty(orderId)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			OrdersList ordersList = ordersListInterfaceDao.queryOrdersListById(Integer.parseInt(orderId));
			if (ordersList == null) {
				logger.error("orderList is not exists");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			Integer orderStartus = ordersList.getStatus();
			Integer mallType = ordersList.getMallType();
			int num = 0;
			Double orderMoney = ordersList.getSumMoney().doubleValue();
			ordersList.setStatus(-1);
			num = ordersListInterfaceDao.updateOrdersList(ordersList);
			if (num < 1) {
				logger.error("update ordersList error");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			String refundStatus = Constant.ERROR;
			if (num > 0) {
				OrdersFlow flow = new OrdersFlow();
				flow.setActionUser(ordersList.getCustomerId());
				flow.setOrdersId(ordersList.getId());
				flow.setStatus(-1);
				List<OrdersFlow> flows = new ArrayList<>();
				flows.add(flow);
				ordersFlowInterfaceService.batchInsertOrdersFlow(flows);
				if (orderStartus - 2 == 0) {
					List list = ordersListInterfaceDao.getGoodsListByOrdersId(Integer.parseInt(orderId));
					Integer count = goodsNormsValueStockInterfaceService.batchUpdateGoodsStock(list);
					if (count < 1) {
						logger.error("update goods stock error");
						resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
						resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
						return resultMap;
					}
					if (mallType - 2 == 0) {
						Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(ordersList.getCustomerId());
						wallet.setRemainingSilverScore(
								new BigDecimal(wallet.getRemainingSilverScore().doubleValue() + orderMoney));
						WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
						expendRecord.setCustomerId(ordersList.getCustomerId());
						expendRecord.setInCome(new BigDecimal(orderMoney));
						expendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
						expendRecord.setFromType(7);
						expendRecord.setOrderType(0);
						expendRecord.setRewardType(1);
						expendRecord.setOrderId(ordersList.getId());
						expendRecord.setCommet("收到订单号为：" + ordersList.getOrdersNo() + "的银积分退还。");
						walletIncomeExpendRecordServiceImpl.insertSelective(expendRecord);
						walletInterfaceImplService.updateWallet(wallet);
						refundStatus = Constant.SUCCESS;
					} else if (mallType - 1 == 0) {
						// 支付宝退款以及微信退款原路返回
						if (ordersList.getPayMode().equals("aliPay")) {
							refundStatus = ALiPay.alipayTradeRefund(ordersList.getOrdersNo(),
									ordersList.getSumMoney().toString());
						} else if (ordersList.getPayMode().equals("weChatPay")) {
							Map<String, Object> refundMap = new HashMap<>();
							refundMap.put("out_trade_no", ordersList.getOrdersNo());
							refundMap.put("total_fee", ordersList.getSumMoney());
							refundMap.put("refund_fee", ordersList.getSumMoney());
							refundStatus = WXPay.wxPayRefundRequest(refundMap);
						}
						WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
						expendRecord.setCustomerId(ordersList.getCustomerId());
						expendRecord.setInCome(new BigDecimal(orderMoney));
						expendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
						expendRecord.setFromType(6);
						expendRecord.setOrderType(0);
						expendRecord.setRewardType(2);
						expendRecord.setOrderId(ordersList.getId());
						expendRecord.setCommet("收到订单号为：" + ordersList.getOrdersNo() + "的现金退还。");
						walletIncomeExpendRecordServiceImpl.insertSelective(expendRecord);
					}
				}
				refundStatus = Constant.SUCCESS;
			}
			if (refundStatus.equals(Constant.SUCCESS)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, new HashMap() {
					{
						put(Constant.MSG, "订单取消成功");
					}
				});
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			}
			return resultMap;
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	@Override
	public Map<String, Object> queryOrdersDetails(String orderIds, Integer customerId) throws ServiceException {
		return ordersDetails(orderIds, customerId, Constant.ORDERS_QUERY_DETAILS);
	}

	@Override
	public Map<String, Object> updateQueryOrdersPayDetails(String orderIds, Integer customerId)
			throws ServiceException {
		return ordersDetails(orderIds, customerId, Constant.ORDERS_QUERY_PAY);
	}

	@Override
	public void deleteOrdersListStatus0(Integer customerId) throws ServiceException {
		try {
			ordersListInterfaceDao.deleteOrdersListStatus0(customerId);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @Title: queryGoodsInfoOfReturnGoods @Description: 查询退换货的商品信息 @param
	 *         orderId @param goodsId @param goodsNormsValueId @return @throws
	 *         ServiceException @return Map<String,Object> @throws
	 */
	@Override
	public Map<String, Object> queryGoodsInfoOfReturnGoods(String orderId, String goodsId, String goodsNormsValueId)
			throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			if (orderId == null || "".equals(orderId) || goodsId == null || "".equals(goodsId)
					|| goodsNormsValueId == null || "".equals(goodsNormsValueId)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			Map map = ordersListInterfaceDao.getGoodsInfoOfReturnGoods(Integer.valueOf(orderId),
					Integer.valueOf(goodsId), Integer.valueOf(goodsNormsValueId));
			if (map != null) {
				Map tempMap = new HashMap();
				tempMap.put("goodsInfo", map);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, tempMap);
				return resultMap;
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
				return resultMap;
			}
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * @package com.sayimo.school.mall.module.order.service
	 * @author chenpy
	 * @Title:
	 * @Description: 获取物流信息
	 * @param
	 * @throws ServiceException
	 * @return Map<String,Object>
	 * @date 2016年4月27日
	 */
	public Map<String, Object> getLogisticInfo(Integer orderId, Integer customerId) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> dataMap = new HashMap<>();
		/*
		 * String customerId = request.getParameter("customerId"); String
		 * orderId = request.getParameter("orderId");
		 */
		logger.info("customerId = " + customerId + ", orderId = " + orderId);

		if (customerId == null || orderId == null) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.MSG, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}

		// 判断订单是否存在
		try {
			OrdersList ordersList = ordersListInterfaceDao.queryOrdersListById(orderId);
			if (ordersList == null) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.MSG, Constant.ORDERS_NOT_EXISTS);
				return resultMap;
			}

			/*
			 * if (ordersList.getStatus() == 1 || ordersList.getStatus() == 2 ||
			 * ordersList.getStatus() == -1 || ordersList.getEmsId() == null ||
			 * StringUtils.isEmpty(ordersList.getEMSNo())) {
			 * resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			 * resultMap.put(Constant.MSG,
			 * Constant.ORDERS_STATUS_HAS_NO_LOGISTICS); return resultMap; }
			 */

			// 订单状态为“待支付/待发货/已取消状态不能查看物流”
			if (ordersList.getStatus() == 1 || ordersList.getStatus() == 2 || ordersList.getStatus() == -1
					|| ordersList.getEmsId() == null || StringUtils.isEmpty(ordersList.getEMSNo())) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.MSG, Constant.ORDERS_STATUS_HAS_NO_LOGISTICS);
				return resultMap;
			}

			dataMap.put("ordersNo", ordersList.getOrdersNo());
			dataMap.put("emsNo", ordersList.getEMSNo());
			// 物流公司信息
			Integer emsId = ordersList.getEmsId();
			logger.info("emsId = " + emsId);
			EmsList emsList = emsListDao.getEmsListById(emsId);
			dataMap.put("emsName", emsList.getEmsName());
			Object traces = KdniaoTrackQueryAPI.getOrderTracesByJson(emsList.getEmsCode(), ordersList.getEMSNo());

			logger.error("traces = " + traces);
			if (!traces.getClass().getSimpleName().equals("String")) {
				List<Map<String, Object>> trances = (List<Map<String, Object>>) traces;
				Object[] o = new Object[trances.size()];
				o = trances.toArray(o);
				ArrayUtils.reverse(o);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				dataMap.put("traces", Arrays.asList(o));
				resultMap.put("data", dataMap);
			} else {
				logger.error("can't get Logistic info, traces = " + traces);
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.MSG, Constant.STATUS_ERROR);
				return resultMap;
			}

			logger.info("resultMap = " + JSONUtil.writeValueAsString(resultMap));
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}

		return resultMap;
	}

	public void updateOrderSumMoneyById(Integer ordersId, Double sumMoney) throws ServiceException {
		try {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("ordersId", ordersId);
			paramMap.put("sumMoney", sumMoney);
			ordersListInterfaceDao.updateOrderSumMoneyById(paramMap);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	/**
	 * @package com.sayimo.school.mall.service.ope
	 * @author wangyang
	 * @Title: insertOrdersList
	 * @Description: 换货生成新订单
	 * @param
	 * @throws @return
	 *             int
	 * @date 2016年7月16日
	 */
	@Override
	public int insertOrdersList(OrdersList orders) throws ServiceException {
		try {
			ordersListInterfaceDao.insertOrderList(orders);
			return orders.getId();
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	/**
	 * @Title: queryOrdersNormsInfoById @Description: @param
	 *         orderId @return @return List @throws
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public List queryOrdersNormsInfoById(Integer orderId) throws ServiceException {
		try {
			return ordersListInterfaceDao.queryOrdersNormsInfoById(orderId);
			// return
			// ordersDao.queryObject("com.sayimo.school.mall.dao.ope.OrdersDao.queryOrdersNormsInfoById",
			// ordersId);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * @Title: updateOrdersById @Description: 修改订单状态 @param orders @throws
	 */
	@Override
	public MessageObject updateOrdersById(OrdersList orders) throws ServiceException {
		MessageObject mObject = new MessageObject();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("status", orders.getStatus());
		paramMap.put("id", orders.getId());
		if (orders.getSumMoney() != null) {
			paramMap.put("sumMoney", orders.getSumMoney());
		}
		if (orders.getTotalAmount() != null) {
			paramMap.put("totalAmount", orders.getTotalAmount());
		}

		try {
			mObject.setObject(ordersListInterfaceDao.updateOrdersById(paramMap));
		} catch (DaoException e) {
			logger.debug(e);
			throw new ServiceException("数据修改异常");
		}
		return mObject;
	}

	/**
	 * @package com.sayimo.school.mall.service.ope.impl
	 * @author chenpy
	 * @Title:
	 * @Description:
	 * @param
	 * @throws ServiceException
	 * @throws @return
	 *             String
	 * @date 2016年6月22日
	 */
	public String getNormsValueString(String goodsNormsValueIds) throws ServiceException {
		String[] normsValueIds = goodsNormsValueIds.split(",");
		StringBuilder normsValues = new StringBuilder();
		for (int i = 0; i < normsValueIds.length; i++) {
			Integer normsValueId = Integer.parseInt(normsValueIds[i]);
			logger.info("normsValueId = " + normsValueId);
			if (normsValueId == 0) {
				continue;
			}

			try {
				String normsValue = goodsNormsInfoDao.getNormsValuesById(normsValueId);
				logger.info("normsValue = " + normsValue);
				normsValues.append(normsValue);
			} catch (DaoException e) {
				e.printStackTrace();
			}

			if (i == 0 && !normsValueIds[1].equals("0")) {
				normsValues.append("/");
			}
		}

		return normsValues.toString();
	}

	private BigDecimal getFreeMinConsumption() {
		try {
			String freeminconsumption = baseConfigDao.getConfigByKey(Constant.SYSCONFIG_FREEMINCONSUMPTION);
			logger.info("freeminconsumption = " + freeminconsumption);
			return StringUtils.isNotEmpty(freeminconsumption) ? new BigDecimal(freeminconsumption) : null;
		} catch (DaoException e) {
			logger.error(e);
		}
		return null;
	}

	/**
	 * @Package com.sayimo.maker.commons.wx.pay
	 * @Author 龚益君
	 * @MethodName:callbackWXPay
	 * @Description:微信回调
	 * @param request
	 * @return
	 * @throws Exception
	 * @Date 2017年3月21日,上午11:52:29
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, Object> callbackWXPay(Map map) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Map<String, String> callbackParamMap = map;
			logger.info("callbackParamMap = " + callbackParamMap);
			logger.info("callbackParamMap = " + JSONUtil.writeValueAsString(callbackParamMap));
			logger.info("result_code = " + callbackParamMap.get("result_code") + ", return_code = "
					+ callbackParamMap.get("return_code"));
			if (!"SUCCESS".equals(callbackParamMap.get("result_code"))) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				return resultMap;
			}

			logger.info("attach = " + callbackParamMap.get("attach"));
			if (callbackParamMap.containsKey("attach")) {
				String passbackParams = callbackParamMap.get("attach");
				passbackParams = URLDecoder.decode(passbackParams, "UTF-8");
				logger.info("passbackParams = " + passbackParams);
				Map passBackMap = JSONUtil.readValueToMap(passbackParams);
				resultMap.putAll(passBackMap);
			}

			logger.info("callbackParamMap = " + callbackParamMap);
			logger.info("callbackParamMap = " + JSONUtil.writeValueAsString(callbackParamMap));

			String appId = callbackParamMap.get("app_id"), seller_id = callbackParamMap.get("mch_id"),
					_payPrice = String.valueOf(resultMap.get("_payPrice"));

			Double jPayPrice = Double.valueOf(_payPrice) * 100D,
					total_fee = Double.valueOf(String.valueOf(callbackParamMap.get("total_fee")));
			logger.info("total_amount = " + total_fee + ", _payPrice = " + _payPrice);

			// 比对金额
			if (!resultMap.containsKey("_payPrice") || jPayPrice.compareTo(total_fee) != 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				return resultMap;
			}

			// 不是微信回调（参数被篡改）
			if (!PropertiesUtils.getValue("WX_APPID").equals(appId)
					|| !PropertiesUtils.getValue("WX_MCHID").equals(seller_id)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				return resultMap;
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put("ordersNo", callbackParamMap.get("out_trade_no")); // 订单号
			logger.info("resultMap = " + resultMap);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @MethodName callbackALiPay
	 * @Description 根据支付宝异步返回的订单号和总金额查询是否存在订单
	 * @author wangyang
	 * @date 2017年3月2日 上午9:14:56
	 * @param
	 * @return Integer
	 * @throws Exception
	 */
	@Override
	public String callbackALiPay() throws Exception {
		try {
			String payModel = null;
			String status = Constant.SUCCESS;
			Map callbackParamMap = new HashMap();
			if (request.getParameterMap().size() > 0) {
				logger.info("request.getParameterMap() = " + request.getParameterMap());
				callbackParamMap = ALiPay.callbackALiPay(request); // 支付宝回调
				payModel = "aliPay";
			} else {
				InputStream inputStream = request.getInputStream();
				logger.info("inputStream = " + inputStream);
				StringWriter stringWriter = new StringWriter();
				IOUtils.copy(inputStream, stringWriter);
				logger.info("stringWriter = " + stringWriter.toString());// 微信回调
				Map param = XMLUtil.doXMLParse(stringWriter.toString());
				logger.info(param);
				// callbackParamMap=callbackWXPay(param);
				Map<String, Object> resultMap = new HashMap<String, Object>();

				logger.info("callbackParamMap = " + param);
				logger.info("callbackParamMap = " + JSONUtil.writeValueAsString(param));
				logger.info(
						"result_code = " + param.get("result_code") + ", return_code = " + param.get("return_code"));
				if (!"SUCCESS".equals(param.get("result_code"))) {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				}

				logger.info("attach = " + param.get("attach"));
				if (param.containsKey("attach")) {
					String passbackParams = param.get("attach").toString();
					logger.info("passbackParams = " + passbackParams);
					Map passBackMap = JSONUtil.readValueToMap(passbackParams);
					resultMap.putAll(passBackMap);
				}

				logger.info("callbackParamMap = " + param);
				logger.info("callbackParamMap = " + JSONUtil.writeValueAsString(param));

				String appId = param.get("appid").toString(), seller_id = param.get("mch_id").toString(),
						_payPrice = String.valueOf(resultMap.get("_payPrice"));

				Double jPayPrice = Double.valueOf(_payPrice) * 100D,
						total_fee = Double.valueOf(String.valueOf(param.get("total_fee")));
				logger.info("total_amount = " + total_fee + ", _payPrice = " + _payPrice);

				// 比对金额
				if (!resultMap.containsKey("_payPrice") || jPayPrice.compareTo(total_fee) != 0) {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				}

				// 不是微信回调（参数被篡改）
				if (!PropertiesUtils.getValue("WX_APPID").equals(appId)
						|| !PropertiesUtils.getValue("WX_MCHID").equals(seller_id)) {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				}

				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put("ordersNo", param.get("out_trade_no")); // 订单号
				logger.info("resultMap = " + resultMap);
				payModel = "weChatPay";
				callbackParamMap = resultMap;
				status = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
			}
			if (!callbackParamMap.get(Constant.STATUS).equals(Constant.STATUS_SUCCESS)) {
				return Constant.ERROR;
			}
			String _ordersType = String.valueOf(callbackParamMap.get("_ordersType")),
					_customerId = String.valueOf(callbackParamMap.get("_customerId")),
					_ordersNo = String.valueOf(callbackParamMap.get("ordersNo"));
			String _consumerOrdersNo = "";
			if (String.valueOf(callbackParamMap.get("ordersNo")).substring(0, 3).equals("005")) { // 联盟商二维码扫码支付会有两个订单号
				_consumerOrdersNo = String.valueOf(callbackParamMap.get("_consumerOrdersNo"));
			}

			if (_ordersType.equals("3")) { // 订单支付回调
				OrdersList ordersList = ordersListInterfaceDao.getOrdersListByOrdersNo(_ordersNo);
				if (ordersList.getStatus() > 1) {
					return status;
				} else {
					String _orderIds = String.valueOf(callbackParamMap.get("_orderIds"));
					Map payMap = new HashMap();
					payMap.put("customerId", _customerId);
					payMap.put("payModel", payModel);
					payMap.put("orderIds", _orderIds);
					paySuccess(payMap);
				}
			}

			else if (_ordersType.equals("2")) { // 充值银积分
				WalletIncomeExpendRecord walletIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
						.getWalletIncomeExpendByEmsNo(_ordersNo);
				logger.info("walletIncomeExpendRecord is null");
				if (walletIncomeExpendRecord.getStatus() == 1) {
					return status;
				}

				customerInterfaceImplService.rechargeSilverScoreCallback(Integer.parseInt(_customerId), _ordersNo);

				return status;
			}

			else if (_ordersType.equals("1")) { // 申请创客
				WalletIncomeExpendRecord walletIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
						.getWalletIncomeExpendByEmsNo(_ordersNo);
				logger.info("walletIncomeExpendRecord is null");
				if (walletIncomeExpendRecord.getStatus() == 2) {
					return status;
				}
				String _rewardType = String.valueOf(callbackParamMap.get("_rewardType"));
				customerInterfaceImplService.applyMakerCallback(Integer.parseInt(_customerId), _ordersNo,
						Integer.valueOf(_rewardType));
			}

			else if (_ordersType.equals("4")) { // 扫描联盟商二维码支付
				WalletIncomeExpendRecord producerIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
						.getWalletIncomeExpendByEmsNo(_ordersNo);
				WalletIncomeExpendRecord consumerIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
						.getWalletIncomeExpendByEmsNo(_consumerOrdersNo);
				logger.info("walletIncomeExpendRecord is null");
				if (producerIncomeExpendRecord.getStatus() == 1 && consumerIncomeExpendRecord.getStatus() == 1) {
					return status;
				}

				customerInterfaceImplService.unionScanCodePayCallback(_ordersNo, _consumerOrdersNo);

				return status;
			}

			else if (_ordersType.equals("5")) {
				WalletIncomeExpendRecord walletIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
						.getWalletIncomeExpendByEmsNo(_ordersNo);
				logger.info("walletIncomeExpendRecord is null");
				if (walletIncomeExpendRecord.getStatus() == 1) {
					return status;
				}

				customerInterfaceImplService.upgradeGoldMakerCallback(Integer.parseInt(_customerId), _ordersNo);

				return status;
			}

			return status;
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	/**
	 * @Package com.sayimo.school.mall.module.provider.service.impl
	 * @Author 龚益君
	 * @MethodName:providerConfirmSendGoods
	 * @Description:供应商发货
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2016年7月14日,下午5:36:38
	 */
	@Override
	public Map<String, Object> providerConfirmSendGoods(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Integer providerId = Integer.parseInt(request.getParameter("providerId"));
		Integer ordersId = Integer.parseInt(request.getParameter("ordersId"));
		Integer emsId = Integer.parseInt(request.getParameter("emsId"));
		String emsNo = request.getParameter("emsNo");
		try {
			if (providerId == null || ordersId == null || emsId == null || emsNo == null || providerId.equals("")
					|| ordersId.equals("") || emsId.equals("") || emsNo.equals("")) {
				logger.error("params error");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			OrdersList order = ordersListInterfaceDao.queryOrdersListById(ordersId);
			EmsList emsList = emsListDao.getEmsListById(emsId);
			order.setStatus(3);
			order.setEmsId(emsId);
			order.setEMSNo(emsNo);
			order.setEMSName(emsList.getEmsName());
			Integer count = ordersListInterfaceDao.updateOrdersList(order);
			if (count > 0) {
				dataMap.put(Constant.MSG, "发货成功");
				ordersFlowInterfaceService.insertOrdersFlow(new GenerateOrdersFlowParams(ordersId, providerId, 3));
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, dataMap);
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			}
		} catch (DaoException e) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			e.printStackTrace();
			logger.error(e);
		}
		return resultMap;
	}

	/**
	 * @Package com.sayimo.maker.mall.orders.service.impl
	 * @Author 龚益君
	 * @MethodName:providerReimburse
	 * @Description:商家同意退款
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2017年3月6日,上午9:45:42
	 */
	@Override
	public Map<String, Object> providerReimburse(HttpServletRequest request) throws ServiceException {
		Map resultMap = new HashMap();
		try {
			String orderId = request.getParameter("ordersId");
			if (StringUtils.isEmpty(orderId)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			OrdersList ordersList = ordersListInterfaceDao.queryOrdersListById(Integer.parseInt(orderId));
			if (ordersList == null) {
				logger.error("orderList is not exists");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			int num = 0;
			Double orderMoney = ordersList.getSumMoney().doubleValue();
			ordersList.setStatus(4);
			num = ordersListInterfaceDao.updateOrdersList(ordersList);
			if (num < 1) {
				logger.error("update ordersList error");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			if (num > 0) {
				OrdersFlow flow = new OrdersFlow();
				flow.setActionUser(ordersList.getCustomerId());
				flow.setOrdersId(ordersList.getId());
				flow.setStatus(4);
				List<OrdersFlow> flows = new ArrayList<>();
				flows.add(flow);
				ordersFlowInterfaceService.batchInsertOrdersFlow(flows);
			}
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, new HashMap() {
				{
					put(Constant.MSG, "已同意退款");
				}
			});
			return resultMap;
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * @Package com.sayimo.maker.mall.orders.service.impl
	 * @Author 龚益君
	 * @MethodName:sayimoReimburse
	 * @Description:平台确认退款
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2017年3月7日,下午3:27:01
	 */
	@Override
	public Map<String, Object> sayimoReimburse(HttpServletRequest request) throws ServiceException {
		Map resultMap = new HashMap();
		try {
			String orderId = request.getParameter("ordersId");
			if (StringUtils.isEmpty(orderId)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			OrdersList ordersList = ordersListInterfaceDao.queryOrdersListById(Integer.parseInt(orderId));
			if (ordersList == null) {
				logger.error("orderList is not exists");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			Integer orderStartus = ordersList.getStatus();
			Integer mallType = ordersList.getMallType();
			int num = 0;
			Double orderMoney = ordersList.getSumMoney().doubleValue();
			ordersList.setStatus(5);
			num = ordersListInterfaceDao.updateOrdersList(ordersList);
			if (num < 1) {
				logger.error("update ordersList error");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			String refundStatus = null;
			if (num > 0) {
				OrdersFlow flow = new OrdersFlow();
				flow.setActionUser(ordersList.getCustomerId());
				flow.setOrdersId(ordersList.getId());
				flow.setStatus(5);
				List<OrdersFlow> flows = new ArrayList<>();
				flows.add(flow);
				ordersFlowInterfaceService.batchInsertOrdersFlow(flows);
				if (orderStartus > 2) {
					List list = ordersListInterfaceDao.getGoodsListByOrdersId(Integer.parseInt(orderId));
					Integer count = goodsNormsValueStockInterfaceService.batchUpdateGoodsStock(list);
					if (count < 1) {
						logger.error("update goods stock error");
						resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
						resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
						return resultMap;
					}
					if (mallType - 1 == 0) {
						// 支付宝退款以及微信退款原路返回
						if (ordersList.getPayMode().equals("aliPay")) {
							refundStatus = ALiPay.alipayTradeRefund(ordersList.getOrdersNo(), orderMoney.toString());
						} else if (ordersList.getPayMode().equals("weChatPay")) {
							Map<String, Object> refundMap = new HashMap<>();
							refundMap.put("out_trade_no", ordersList.getOrdersNo());
							refundMap.put("total_fee", orderMoney);
							refundMap.put("refund_fee", orderMoney);
							refundStatus = WXPay.wxPayRefundRequest(refundMap);
						}
						WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
						expendRecord.setCustomerId(ordersList.getCustomerId());
						expendRecord.setInCome(new BigDecimal(orderMoney));
						expendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
						expendRecord.setFromType(6);
						expendRecord.setOrderType(0);
						expendRecord.setRewardType(2);
						expendRecord.setOrderId(ordersList.getId());
						expendRecord.setCommet("收到订单号为：" + ordersList.getOrdersNo() + "的现金退还。");
						walletIncomeExpendRecordServiceImpl.insertSelective(expendRecord);
					}
				}
			}
			if (refundStatus.equals(Constant.SUCCESS)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, new HashMap() {
					{
						put(Constant.MSG, "已成功退款");
					}
				});
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			}
			return resultMap;
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
}
